<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\controller;

use app\admin\model\GeoHash;
use app\api\controller\Esapi;
use app\api\controller\FliggyApi;
use app\api\controller\LvjiApi;
use app\api\controller\OssController;
use app\api\controller\Trip as TripApi;
use \think\Cookie;
use think\Exception;
use think\Db;
use app\admin\model\Product as ProductModel;
use app\admin\model\ProductRecycle as ProductRecycleModel;
use app\admin\model\Pschedule as pscheduleModel;
use app\admin\model\Pactive as pactiveModel;
use app\api\controller\KbxOther;
use app\api\controller\KbxOrder;
use app\api\controller\KbxToken;
use app\api\controller\Poi;
use app\api\model\Poi as PModel;
use app\admin\model\Dayprice as DaypriceModel;
use app\api\model\Standard as SDModel;
use app\api\controller\Standard as SDController;
use app\api\controller\ExportExcel;
use app\api\controller\Common;
use think\Log;
use think\Lang;
use think\Request;
use app\api\model\GroupToursLine as GT;
use think\Validate;

class Product extends User
{
    public $goodsurl='https://c.kuaibangxing.com/quick_help_wap1/#/show/';
    private $customerAttrs = [];
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
//        显示名称-字段名称-是否禁止修改-是否显示-主是否必填-次是否必填
        $this->customerAttrs = [
            '姓名'=>'姓名-name-1-1-1-1',
            '微信号'=>'微信号-wechat-0-1-0-0',
            '手机号'=>'手机号-mobile-1-1-1-0',
            '身份证号'=>'身份证号-idNo-0-0-0-0',
            '年龄'=>'年龄-age-0-0-0-0',
            '性别'=>'性别-gender-0-0-0-0',
            '体重'=>'体重-weight-0-0-0-0',
            '车型'=>'车型-carType-0-0-0-0',
        ];
    }
    //产品列表
    public function index()
    {
        $post = $this->request->post();

        $exportFlag = request()->param('exportFlag');//是否为导出

        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page) || isset($exportFlag)){
            //条件从缓存取出
            $post=Cookie::get('productlist');
        }else{
            //把条件写入缓存
            Cookie::set('productlist',$post);
        }

        $nowtime = time();
        $where = [];
        if (isset($post['tripname']) and !empty($post['tripname'])) {
            $where['p.name|p.id|p.item_num'] = ['like', '%' . trim($post['tripname']) . '%'];
        }
        if (isset($post['days']) and !empty($post['days'])) {
            $where['p.days'] = $post['days'];
        }
        if (isset($post['group_type']) and !empty($post['group_type'])) {
            $where['p.group_type'] = $post['group_type'];
        }
        if (isset($post['supplier_id']) and !empty($post['supplier_id'])) {
            $where['p.supplier_id'] = $post['supplier_id'];
        }
        if (isset($post['service_type']) and $post['service_type']!=='') {
            $where['p.service_type'] = $post['service_type'];
        }
        if (isset($post['start_city']) and !empty($post['start_city'])) {
            $where['p.start_city'] = $post['start_city'];
        }
        if (isset($post['service_status']) and $post['service_status']!=='') {
            if($post['service_status']==1){//售卖中
                $where['p.sale_starttime'] = ['LT',$nowtime];
                $where['p.sale_endtime'] = ['GT',$nowtime];
            }elseif($post['service_status']==2){//预售中
                $where['p.sale_starttime'] = ['GT',$nowtime];
            }else{//已下架
                $where['p.sale_endtime'] = ['LT',$nowtime];
            }
        }
        if (isset($post['service_language']) and $post['service_language']!=='') {
            $where['p.service_language'] = $post['service_language'];
        }
        if (isset($post['check_status']) and $post['check_status']!=='') {
            $where['p.check_status'] = $post['check_status'];
        }
        if (!empty($post['supplierItemCode']) && $post['supplierItemCode']!=='') {
            $where['p.supplier_item_code'] = ['like', '%' . trim($post['supplierItemCode']) . '%'];
        }
        if (!empty($post['supplier_admin_id'])) {
            $where['sa.supplier_admin_id'] = $post['supplier_admin_id'];
        }
        if(!empty($post['supplier_id'])){
            $suplier_admin_where['company_id'] = $post['supplier_id'];
        }
        $suplier_admin_where['is_use'] = 1;
        $supplier_admin = db('supplier_admin')
            ->field('supplier_admin_id,supplier_name as supplier_admin_name')
            ->where($suplier_admin_where)->select();
        $this->assign('supplier_admin',$supplier_admin);
        //tob是否上架
        if (isset($post['isTob']) && $post['isTob']!==''){
            if($post['isTob']==1){
                $where['s.show_toB'] = 1;
            }elseif($post['isTob']==2){
                $exp =new \think\db\Expression('is null or s.show_toB = 0');
                $where['s.show_toB'] = ['exp',$exp];
            }
        }

        $productModel = new ProductModel();

        $search_page = 20;
        //导出查询条件
        if($exportFlag==1){
            $search_page = 10000;
        }

        $where['p.use_type'] = 1;
        $product = $productModel->alias('p')
            ->join('standardtrip st','st.trip_id=p.id','left')
            ->join('standard s','s.id=st.sid','left')
            ->join('supplier_admin sa','sa.supplier_admin_id=p.supplier_admin_id','left')
            ->where($where)
            ->field('p.*,s.show_toB,s.id as standard_id,s.page_index,sa.supplier_name as supplier_admin_name')
            ->order('p.update_time desc')
            ->paginate($search_page);

        $cityData=Db::name('city')->where("type","CITY")->field("id,name")->select();
        $adminData=Db::name('admin')->field("id,nickname")->select();
        $adminArr = [];
        $cityArr = [];
        foreach ($adminData as $k=>$v) {
            $adminArr[$v['id']] = $v['nickname'];
        }
        foreach ($cityData as $k=>$v) {
            $cityArr[$v['id']] = $v['name'];
        }
        $product_ids = [];
        for($x=0 ; $x<count($product) ; $x++){
            if(!empty($adminArr[$product[$x]['adminid']])){
                $product[$x]['admin']=$adminArr[$product[$x]['adminid']];
            }else{
                $product[$x]['admin']="";
            }
            if(!empty($cityArr[$product[$x]['start_city']])){
                $product[$x]['start_city']=$cityArr[$product[$x]['start_city']];
            }else{
                $product[$x]['start_city']="";
            }
            if(!empty($adminArr[$product[$x]['update_admin']])){
                $product[$x]['update_admin']=$adminArr[$product[$x]['update_admin']];
            }else{
                $product[$x]['update_admin']="";
            }

            $sale_starttime = $product[$x]['sale_starttime'];
            $sale_endtime = $product[$x]['sale_endtime'];
            $service_status = 0;//状态
            if($nowtime>=$sale_starttime && $nowtime<=$sale_endtime){
                $service_status = 1;
            }elseif($sale_starttime>$nowtime){
                $service_status = 2;
            }
            $product[$x]['service_status'] = $service_status;
            //查询是否存在FAQ
            $faq_flag = 0;
            $faq = db("faq")
                ->where("groupid",$product[$x]['id'])
                ->where("typeid",1)
                ->where("deleted",0)
                ->find();
            if(!empty($faq)){
                $faq_flag = 1;
            }

            $product[$x]['faq_flag'] = $faq_flag;
            $product_ids[] = $product[$x]['id'];

        }
        //供应商   不能放上面，引入类构造方法会过滤html标签
        list($supplier,$supplierNameArr) = $this->getAllSupplierList();
        $this->assign('supplier',$supplier);
        if(!empty($product_ids)){
            $pro_attachments = db('product_attachments')
                ->field('product_id,count(id) as count')
                ->where([
                    'is_delete'=>0,
                    'product_id'=>['in',$product_ids]
                ])->group('product_id')->select();
        }
        foreach ($product as $k=>$v) {
            if(!empty($v['supplier_id'])){
                if($v['supplier_id']=='999999'){
                    $product[$k]['supplier_name'] = '自营';
                }elseif($v['supplier_id']=='77777'){
                    $product[$k]['supplier_name'] = '无';
                }elseif($v['supplier_id']=='1000000'){
                    $product[$k]['supplier_name'] = '其他';
                }else{
                    $product[$k]['supplier_name'] = !empty($supplierNameArr[$v['supplier_id']]) ? $supplierNameArr[$v['supplier_id']] : '';
                }
            }else{
                $product[$k]['supplier_name'] = '';
            }

            //附件内容
            $product[$k]['attachments'] = 0;
            foreach ($pro_attachments as $attach_k=>$attach_v){
                if($attach_v['product_id']==$v['id']){
                    $product[$k]['attachments'] = (int) $attach_v['count'];
                }
            }
        }
        //服务类型
        $serviceType = db("service_type")->select();
        $this->assign('serviceType',$serviceType);
        $this->assign('product',$product);
        $this->assign('cityData',$cityData);
        $this->assign('wherelist',$post);

        //导出方法
        if($exportFlag==1){
            $dataArr = array();
            $ExportExcel = new ExportExcel();
            foreach ($product as $k=>$v) {
                $data = array();
                $data['id'] = $v['id'];
                $data['name'] = $v['name'];
                $data['item_num'] = $v['item_num'];
                $data['supplier_name'] = !empty($v['supplier_name']) ? $v['supplier_name'] : '';
                $data['supplier_item_code'] = !empty($v['supplier_item_code']) ? $v['supplier_item_code'] : '';
                $data['days'] = $v['days'];
                $data['start_city'] = $v['start_city'];
                if($v['service_status']==1){
                    $data['service_status'] = "售卖中";
                }elseif($v['service_status']==2){
                    $data['service_status'] = "预售中";
                }else{
                    $data['service_status'] = "已下架";
                }

                if(!empty($v['show_toB']) && $v['show_toB']==1){
                    $data['show_toB'] = "已上架";
                }else{
                    $data['show_toB'] = "已上架";
                }

                $dataArr[] = $data;
            }

            $table_head = array("产品ID","产品名称","产品code","供应商","供应商产品号","天数","出发城市","售卖状态","toB上架");
            $ExportExcel->exportExcel($dataArr, $table_head, "产品列表");
        }else{
            return $this->fetch();
        }
    }

    //提交信息创建产品
    public function info(){
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();
            $adminid = Cookie::get('admin');
            $post['adminid'] = $adminid;
            $post['use_type'] = 1;
            $post['days'] = $post['days']>0 ? $post['days'] : 1;
            $post['update_admin'] = $adminid;
            $post['update_time'] = time();
            $post['sale_starttime'] = time();
            $post['sale_endtime'] = time();

            $model = new ProductModel();
            if(false == $model->allowField(true)->save($post)) {
                return $this->error('新增失败');
            } else {
                $productid = $model->getLastInsID();
                $scheduleModel = new pscheduleModel();
                $days = $post['days'];
                $nowtime = time();
                for ($i=1;$i<=$days;$i++){
                    //添加schedule
                    $daysData = [];
                    $daysData['groupid'] = $productid;
                    $daysData['displayorder'] = $i;
                    $daysData['create_time'] = $nowtime;
                    $daysData['update_time'] = $nowtime;

                    $scheduleModel->allowField(true)->create($daysData);
                    $scheduleid = $scheduleModel->getLastInsID();

                    //添加active
                    $activeData = [];
                    $activeData['typeid'] = 3;
                    $activeData['activeType'] = 1;
                    $activeData['groupid'] = $scheduleid;
                    $activeData['displayorder'] = 1;
                    $activeData['create_time'] = $nowtime;
                    $activeData['update_time'] = $nowtime;

                    $activeModel = new pactiveModel();
                    $activeModel->allowField(true)->create($activeData);
                }

                //新增产品成功 增加管理员积分记录
                (new KbxOrder())->addAdminScore('product',$productid,'新增产品ID为'.$productid.'的'.$post['name']);

                return $this->success('新增成功',"", $productid);
            }
        } else {
            $where['type'] = "CITY";
            $where['deleted'] = 0;
            $city = db("city")->where($where)->field("id,name")->select();
            $cityJson = json_encode($city,JSON_UNESCAPED_UNICODE);
            $this->assign('cityJson',$cityJson);
            $this->assign('city',$city);

            //供应商   不能放上面，引入类构造方法会过滤html标签
            list($supplier,$supplierNameArr) = $this->getSupplierList();
            $this->assign('supplier',$supplier);

            return $this->fetch();
        }
    }

    //导入产品创建
    public function importInfo(){
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            //导入行程id串
            if(!empty($post['tripids'])){
                $tripids = $post['tripids'];
                $tripsArr = explode(",",$tripids);
            }else{
                $tripsArr = [];
            }
            if(!empty($post['productids'])){
                $productids = $post['productids'];
                $productsArr = explode(",",$productids);
            }else{
                $productsArr = [];
            }
            if(empty($tripsArr) && empty($productsArr)){
                return $this->error("至少要选择一个行程导入！");
            }

            $adminid = Cookie::get('admin');
            $post['adminid'] = $adminid;
            $post['use_type'] = 1;
            $post['days'] = $post['days']>0 ? $post['days'] : 1;
            $post['update_admin'] = $adminid;
            $post['update_time'] = time();
            $post['sale_starttime'] = time();
            $post['sale_endtime'] = time();

            $model = new productModel();
            if(false == $model->allowField(true)->save($post)) {
                return $this->error('新增失败');
            } else {
                $productid = $model->getLastInsID();
                $res = $this->importProductByTripIds($tripsArr,$productsArr,$productid);
                if($res){
                    return $this->success('新增成功',"",$productid);
                }else{
                    return $this->error('新增失败');
                }
            }
        }
    }

    //详细定制页
    public function productmake(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $model = new ProductModel();
        $weekarray=array("日","一","二","三","四","五","六");
        $trip = [];
        //是否关联商品
        $existGoods = false;
        $this->assign("existGoods",$existGoods);
        $is_domestic = false;
        if($id > 0) {
            $trip = $model->where("id",$id)->find();
            $trip['start_go_time'] = $trip['start_go_time']>0 ? date("Y-m-d",$trip['start_go_time']) : '';
            $tripid = $id;
            $schedule = db("pschedule")->where("groupid",$id)->order("displayorder asc")->select();
            //判断是否为国内城市 国内城市使用amap 国外使用googlemap
            if(!empty($trip['start_city'])){
                $china = db('city')->where('eng_name','Chinese Mainland')->find();
                $startCityInfo = db('city')->where([
                    'id'=>$trip['start_city'],
                    'groupid'=>$china['id']
                ])->find();
                if(!empty($startCityInfo)) $is_domestic = true;
            }
            $day = 1;
            //默认显示遮罩
            $trip['is_show_shadow'] = 1;
            foreach ($schedule as $k=>$v) {
                $schedule_id = $v['id'];
                $active = db("pactive")
                    ->where("groupid",$schedule_id)
                    ->order("displayorder asc")
                    ->field("id,title,poiname,poiid,cityid,time,activeType,airport_lat,airport_lng")
                    ->select();

                if(!empty($active)){
                    foreach ($active as $k_a=>$v_a) {
                        if(!empty($v_a['cityid']) && $v_a['cityid']>0){
                            $where['deleted'] = 0;
                            $where['groupid'] = $v_a['cityid'];

                            $poiArr = [];
                            if($v_a['activeType']==1){//POI
                                $where['typeid'] = ['in',[1,2,3,4,6]];//1景点，3演出赛事，4限时活动，6其他，11美食
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }elseif($v_a['activeType']==2 || $v_a['activeType']==3){//接机 送机
                                $airportData = $this->kbxGetAirport($v_a['cityid']);
                                $airport = [];
                                foreach ($airportData as $k_air=>$v_air) {
                                    $airportName = (isset($v_air['nameen']) && $v_air['nameen']!=='') ? $v_air['name']."(".$v_air['nameen'].")" : $v_air['name'];
                                    $airport[] = ['id'=>$v_air['id'],'name'=>$airportName];
                                    $poiArr = $airport;
                                }
                            }elseif($v_a['activeType']==4){//酒店
                                $where['typeid'] = 5;//酒店
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }elseif($v_a['activeType']==5){//特色体验

                            }elseif($v_a['activeType']==6){//其他

                            }elseif($v_a['activeType']>10){
                                $where['typeid'] = $v_a['activeType'];
                                $poiArr = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
                            }

                            $active[$k_a]['poiArr'] = $poiArr;

                            //加入距离
                            $activeDistance = $this->getActiveDistance($k_a,$active);
                            $active[$k_a]['limit'] = $activeDistance;
                        }else{
                            $active[$k_a]['poiArr'] = [];
                        }
                    }
                }

                $schedule[$k]['active'] = $active;
                $schedule[$k]['dayNum'] = $day;
                $schedule[$k]['week'] = "周".$weekarray[date("w",strtotime($v['time']))];

                $_trans_type_arr = [];
                if(!empty($v['transport_typeids'])){
                    //不显示遮罩
                    $trip['is_show_shadow'] = 0;
                    $trans_type_arr = explode(",",$v['transport_typeids']);
                    if(!empty($trans_type_arr)){
                        foreach ($trans_type_arr as $value){
                            $trans_type_item = [
                                'id'=>$value,
                                'title'=>$this->getTransportTitle($value),
                            ];
                            $_trans_type_arr[] = $trans_type_item;
                        }
                    }
                }
                $schedule[$k]['transportList'] = $_trans_type_arr;

                $day++;
            }

            //核价数据
            $this->assign('totalHotelPrice',$trip['totalHotelPrice']);
            $this->assign('totalAirportPrice',$trip['totalAirportPrice']);
            $this->assign('totalDrivePrice',$trip['totalDrivePrice']);
            $this->assign('totalTransPrice',$trip['totalTransPrice']);
            $this->assign('airportPrice_btn',$trip['airportPrice_btn']);
            $this->assign('hotelPrice_btn',$trip['hotelPrice_btn']);
            $this->assign('drivePrice_btn',$trip['drivePrice_btn']);
            $this->assign('carPrice_btn',$trip['carPrice_btn']);

            $this->assign('schedule',$schedule);
            $adminArr = db("admin")->field("id,nickname")->select();
            $adminIdArr = [];
            foreach ($adminArr as $admin_k=>$admin_v) {
                $adminIdArr[$admin_v['id']] = $admin_v['nickname'];
            }
            $trip['sale_starttime'] = $trip['sale_starttime']!=='' ? date("Y-m-d",$trip['sale_starttime']) : '';
            $trip['sale_endtime'] = $trip['sale_endtime']!=='' ? date("Y-m-d",$trip['sale_endtime']) : '';
            $trip['update_admin'] = !empty($trip['update_admin']) ? $adminIdArr[$trip['update_admin']] : '';

            //过滤html标签
            $trip['saletime_more'] = strip_tags($trip['saletime_more']);
            $trip['cost_price_out'] = strip_tags($trip['cost_price_out']);
            $trip['cost_price_busy'] = strip_tags($trip['cost_price_busy']);
            $trip['ota_price_out'] = strip_tags($trip['ota_price_out']);
            $trip['ota_price_busy'] = strip_tags($trip['ota_price_busy']);
            $trip['own_price_out'] = strip_tags($trip['own_price_out']);
            $trip['own_price_busy'] = strip_tags($trip['own_price_busy']);
            $trip['description'] = strip_tags($trip['description']);
            $trip['introduction'] = strip_tags($trip['introduction']);
            $trip['careful'] = strip_tags($trip['careful']);
            $trip['price'] = strip_tags($trip['price']);
            $trip['priceno'] = strip_tags($trip['priceno']);
            $trip['back'] = strip_tags($trip['back']);

            //获取tag
            $tagArr = $trip['tag_id'];
            $tagArr = explode(',',$tagArr);
            if(!empty($tagArr[0])){
                $tagdata = Array();
                foreach($tagArr as $key=>$value){
                    $tags = Db::name('tag')->where("tag_id",$value)->field("tag_name,tag_id")->find();
                    $tagdata[$key] = $tags;
                }
            }else{
                $tagdata='';
            }
            $this->assign('tagdata',$tagdata);
            //套餐
            $package_list =	db('product_package')->where('product_id',$id)->where('status',1)->select();
            //商品信息
            $goodsInfo = db('goods')->where('goods_tcode',$trip['item_num'])->find();
            $existGoods = !empty($goodsInfo)?true:false;
            if(!empty($goodsInfo['need_confirm'])) {
                $trip['need_confirm'] = $goodsInfo['need_confirm'];
            }
            if(!empty($goodsInfo)){
                $trip['goodsImages'] = array_values(array_filter(explode(',',$goodsInfo['goods_image'])));
                $trip['goodsVideo'] = $goodsInfo['goods_video']??'';
            }
            //标品信息
            $standardInfo = db('standard s')
                ->where('p.id',$id)
                ->join('standardtrip st','st.sid=s.id','left')
                ->join('product p','st.trip_id=p.id','left')
                ->find();
            if(!empty($standardInfo['allow_everyone_quote'])){
                $trip['allow_everyone_quote'] = $standardInfo['allow_everyone_quote'];
            }
            if(!empty($standardInfo['is_group_exhibition'])){
                $trip['is_group_exhibition'] = $standardInfo['is_group_exhibition'];
            }
            $this->assign('standardInfo',$standardInfo);

            //获取推荐产品的ID集合
            if(!empty($trip['recommend_standard_ids'])){
                $selectedRecommendStandard = db('standard')->where(['id'=>['in',$trip['recommend_standard_ids']]])->field('id,name')->select();
                $this->assign('selectedRecommendStandard',$selectedRecommendStandard);
            }

            //虚拟产品
            if($trip['service_type']==18){
                $electronic = db('product_electronic')->where([
                    'electronic_pro_id'=>$id
                ])->find();
                if(!empty($electronic)){
                    $trip = array_merge($trip->toArray(),$electronic);
                }
            }
        }else{
            $trip['sale_starttime'] = '';
            $trip['sale_endtime'] = '';
            $this->assign('airportPrice_btn',0);
            $this->assign('hotelPrice_btn',0);
            $this->assign('drivePrice_btn',0);
            $this->assign('carPrice_btn',0);
            $this->assign('tagdata','');
            $tripid = 0;
            $package_list = [];
        }
        //是否为国内服务城市
        $this->assign("is_domestic",$is_domestic);
        $where_city['type'] = "CITY";
        $where_city['deleted'] = 0;
        //按照中文名称排序
        $city_order = new \think\db\Expression("CONVERT(name USING gbk) asc");
        $city = db("city")->where($where_city)->field("id,name")->order($city_order)->select();
        $tripcustomer = db("tripcustomer")->where("tripid",$tripid)->find();

        //服务类型
        $serviceType = db("service_type")->select();
        $this->assign('city',$city);
        $this->assign('existGoods',$existGoods);
        $this->assign('goodsData',$goodsInfo??[]);
        $this->assign('serviceType',$serviceType);
        $this->assign('tripid',$tripid);
        $this->assign('trip',$trip);
        $this->assign('customer',$tripcustomer);
        $this->assign('kbx_url',config('kbx_url'));
        //新建poi所需城市列表
        $ourcity = Db::name('city')->where(['deleted'=>0,'groupid'=>['neq',0]])->field('id,concat(name,"(",eng_name,")") as name')->order("sort_weight desc")->select();
        $this->assign('ourcity',$ourcity);

        //供应商   不能放上面，引入类构造方法会过滤html标签
        list($supplier,$supplierNameArr) = $this->getAllSupplierList();
        $this->assign('supplier',$supplier);

        //扩展包车
        $transport = $this->getTransportTitle();
        $this->assign('transport',$transport);

        //售价日历
        $dailyPrice = [];
        if(!empty($trip['sale_starttime']) && !empty($trip['sale_endtime'])){
            $dailyPrice = db("product_dailyprice")->where(["product_id"=>$tripid,'time'=>['between',[$trip['sale_starttime'],$trip['sale_endtime']]]])->order("id asc")->select();
        }
        //按天封装数据
        $dailyPriceData = [];
        if(!empty($dailyPrice)){
            foreach ($dailyPrice as $value){
                $dailyPriceData[$value['time'].",".$value['package_id']][] = $value;
            }
        }
        $this->assign('dailyPriceData',(string)json_encode($dailyPriceData));

        $this->getPriceForMake($tripid);
        //展示额外价格
        $extra_cost = $this->getExtraCostByProduct($tripid);
        $this->assign("extra_cost",$extra_cost);
        //渲染行程价格数据

        //标签列表
        $tag = db('tag')->where('tag_type','2')->where('tag_status','NEQ','2')->select();
        $this->assign("tag",$tag);
        $this->assign("packageList",$package_list);
        //货币类型
        $currencyCodeList = (new Common())->getCurrencyListByCity();
        $this->assign("currencyCodeList",json_encode($currencyCodeList));
        //获取税率
        $exchangeList = db('exchange')->select();
        $this->assign("exchangeList",json_encode($exchangeList));

        //POI分类 前期做了部分拆分 以至于需要单独设计
        $poiClassifyList = $this->getPoiClassifyList();
        $global_active_type_arr = $this->getGlobalActiveTypeList();

        $this->assign("poiClassifyList",$poiClassifyList);
        $this->assign("global_active_type_arr",json_encode($global_active_type_arr));
        //是否为特色商品
        $FeaturedProduct = !empty($trip['service_type']) && $trip['service_type']==14?true:false;
        $this->assign("FeaturedProduct",$FeaturedProduct);
        //节点放案和文本方案的标志
        $textPlan =!empty($trip['is_text_plan']) && $trip['is_text_plan']==1?true:false;
        $this->assign("textPlan",$textPlan);
        //控制是否开启切换文本方案功能
        $this->assign('isOpenTextPlan',config('isOpenTextPlan'));

        //推荐产品列表
        $allRecommendStandard = (new SDController())->getAllRecommendStandardList($trip['supplier_id']??'');
        $this->assign('allRecommendStandard',$allRecommendStandard);

        $product_currency = $trip['currency']??'CNY';
        $currency_symbol = '￥';
        // $currencyList = (new Common())->getCurrencyListByCity();
        // foreach ( $currencyList as $currency_v){
        //     if($product_currency==$currency_v['currency_code']){
        //         $currency_symbol = $currency_v['currency_symbol'];break;
        //     }
        // }
        //货币单位
        $this->assign('product_currency',$currency_symbol);

        //出行人信息
        $customerAttrsConfig = $this->customerAttrs;

        if(!empty($trip['customer_info_config'])){
            $customerAttrs = explode(',',$trip['customer_info_config']);
            foreach ($customerAttrs as $value){
                $attr_value = explode('-',$value);
                if(!empty($customerAttrsConfig[$attr_value[0]])){
                    $customerAttrsConfig[$attr_value[0]] = $value;
                }
            }
        }
        $this->assign('customerAttrs',implode(',',$customerAttrsConfig));
        $customer_info_config = [];
        foreach ($customerAttrsConfig as $value){
            $attr = explode('-',$value);
            if(!empty($attr['3'])){
                $customer_info_config[] = $value;
            }
        }
        $trip['customer_info_config'] = implode(',',$customer_info_config);
        $this->assign("customerInfoConfig",$trip['customer_info_config']);

        $electronicSupplier = $this->electronicSupplier();
        $this->assign("electronicSupplier",$electronicSupplier);
        return $this->fetch();
    }

    public function deltrip()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        //删除前保存备份
        if(empty($id)) return $this->error('获取产品失败');
        $product = db('product')->find($id);
        if(empty($product)) return $this->error('获取产品失败');
        //上线的产品不支持直接删除 需要下线后才能删除
        $standardtrip = db('standardtrip')->where('trip_id',$id)->find();
        if(!empty($standardtrip['sid'])){
            $standard = db('standard')->find($standardtrip['sid']);
            if(!empty($standard)){
                if($standard['show_toB'] > 0) return $this->error(Lang::get('上线的产品不支持直接删除！请下线后操作'));
            }
        }

        $save_data['name'] = $product['name'];
        $save_data['code'] = $product['item_num'];
        $save_data['json_data'] = json_encode($product);
        db::startTrans();
        try{
            db('product_recycle')->insert($save_data);
            db('product')->where('id',$id)->delete();
            db::commit();
            return $this->success('删除成功');
        }catch (Exception $e){
            db::rollback();
            return $this->error('删除失败,原因：'.$e->getMessage());
        }
    }
    //查看删除的产品列表
    public function recyclelist()
    {
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post = Cookie::get('recyclelist');
        } else {
            //把条件写入缓存
            Cookie::set('recyclelist',$post);
        }
        $where = '';
        if (isset($post['tripname']) and !empty($post['tripname'])) {
            $where['p.name|p.code'] = ['like', '%' . trim($post['tripname']) . '%'];
        }
        $productModel = new ProductRecycleModel();
        $search_page = 20;
        $product = $productModel->alias('p')
            ->where($where)
            ->order('p.id desc')
            ->paginate($search_page);

        $adminData=Db::name('admin')->field("id,nickname")->select();
        foreach ($product as $key=>$value){
            $product_data = json_decode($value['json_data'],true);
            $product[$key]['update_admin'] = '';
            $product[$key]['old_id'] = $product_data['id']??'';
            $product[$key]['update_time'] = $product_data['update_time']??'';
            foreach ($adminData as $admin_key=>$admin_value){
                if($product_data['update_admin']==$admin_value['id']){
                    $product[$key]['update_admin'] = $admin_value['nickname'];
                    break;
                }
            }
        }
        $this->assign('product',$product);
        $this->assign('wherelist',$post);
        return $this->fetch();
    }
    //还原产品
    public function recycle()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $product = db('product_recycle')->find($id);
        if(empty($product)) return $this->error('获取产品失败');
        db::startTrans();
        try{
            $old_product = json_decode($product['json_data'],true);
            db('product')->insert($old_product);
            db('product_recycle')->where('id',$id)->delete();
            db::commit();
            return $this->success('还原成功');
        }catch (Exception $e){
            db::rollback();
            return $this->error('还原失败,原因：'.$e->getMessage());
        }
    }

    public function preview(Request $request)
    {
        $id = $request->param('id');
        if(empty($id)) return $this->error('产品预览错误！');
        $use_thumb = $request->param('use_thumb',false);
        $trip = Db::name('product')->find($id);
        $sale_starttime = !empty($trip['sale_starttime']) ? date("Y-m-d",$trip['sale_starttime']) : '';
        $sale_endtime = !empty($trip['sale_endtime']) ? date("Y-m-d",$trip['sale_endtime']) : '';
        $saletime = '';
        if($sale_starttime!=='' && $sale_endtime!==''){
            $saletime = $sale_starttime." ~ ".$sale_endtime;
        }
        $this->assign('saletime',$saletime);
        $allcitys = $allcityLatLngs = [];
        $schedules = Db::name('pschedule')->where('groupid',$id)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)){
            $actives = db('pactive a')
                ->join("city c","c.id=a.cityid",'left')
                ->join("poi p","p.id=a.poiid",'left')
                ->field("a.*,c.lat as c_lat,c.lng as c_lng,p.introduce as p_introduce,p.lat,p.lng,p.thumb as poi_thumb,p.eng_introduce,p.open_time,p.ticket,p.price,p.grade,p.description,p.thumb,p.source,p.mobile,p.ticket_url,p.address")
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }else{
            $actives = [];
        }
        $showpwd = $this->request->has('prevadminpwd') ? $this->request->get('prevadminpwd') : 0;
        if($showpwd){
            $this->assign('showpwd',$showpwd);
        }
        //默认值为空
        foreach ($schedules as $key=>$value){
            $schedules[$key]['child'] = [];
            $schedules[$key]['citys'] = [];
        }
        foreach ($actives as $key=>$value){
            //所有城市经纬度
            $cityLatLng = [
                'lat'=>floatval($value['c_lat']),
                'lng'=>floatval($value['c_lng'])
            ];
            if(end($allcityLatLngs)!=$cityLatLng){
                array_push($allcityLatLngs,$cityLatLng);
            }
            if(!in_array($value['cityname'],$allcitys)){
                array_push($allcitys,$value['cityname']);
            }

            if(empty($value['poiImg'])){
                $value['thumb'] = '';
            }else{
                $value['thumb'] = $value['poiImg'];
            }
            $thumb_img_arr = [];
            if(!empty($value['thumb'])){
                $thumb_img_arr = array_filter(explode(',',$value['thumb']));
                if(!empty($thumb_img_arr) && $use_thumb){
                    foreach ($thumb_img_arr as $thumb_img_k=>$thumb_img_v){
                        $thumb_img_arr[$thumb_img_k] = (new OssController())->getOssThumbImg($thumb_img_v,360,240);
                    }
                }
            }
            $value['thumb'] = $thumb_img_arr;
            //其他图片
            if(!empty($value['other_images'])){
                $imageArr = explode(",",$value['other_images']);
                $imageArr = array_filter($imageArr);
                if($use_thumb){
                    foreach ($imageArr as $image_key=>$image_value){
                        $imageArr[$image_key] = (new OssController())->getOssThumbImg($image_value,360,240);
                    }
                }

                $value['image_arr'] = $imageArr;
            }else{
                $value['image_arr'] = [];
            }
            $value['name_id'] = "name_".$value['id'];
            $city_name = "";
            if(!empty($value['poiname'])){
                $city_name = $value['poiname'];
            }elseif(!empty($value['cityname'])){
                $city_name = $value['cityname'];
            }elseif(!empty($value['title'])){
                $city_name =$value['title'];
            }

            if($value['activeType']==2 || $value['activeType']==3){
                $value['ticket'] = '';
                $value['open_time'] = '';
                $value['ticket_url'] = '';
                $value['eng_introduce'] = '';
                $value['description'] = '';
                $value['price'] = '';
                $value['poiImg'] = '';
                $value['source'] = '';
                $value['address'] = '';
                $value['grade'] = '';
                $value['mobile'] = '';
                $value['poi_content'] = '';
                $value['image_arr'] = '';
                $value['thumb'] = '';
            }

            //封装结构
            foreach ($schedules as $k=>$v){
                if($v['id']==$value['groupid']){
                    $schedules[$k]['child'][] = $value;
                    if(!empty($city_name)){
                        $schedules[$k]['citys'][] = $city_name;
                    }
                    break;
                }
            }
        }

        foreach($schedules as $key=>$value){
            $daytitle  = $value['title'];
            if($value['title']!==""){
                if(substr($value['title'],0,1)==","){
                    $daytitle = substr($value['title'],1);
                }
            }
            $activeKeyArr=[];
            foreach ($value['child'] as $k=>$v){
                if($v['showkey']==1){
                    if($v['typeid']==3){
                        $keytitle = $v['poiname'];
                    }elseif($v['typeid']==2){
                        $keytitle = $v['cityname'];
                    }else{
                        $keytitle = $v['title'];
                    }

                    $activeKeyArr[] = [
                        'id'=>"name_".$v['id'],
                        'title'=>$keytitle,
                    ];
                }
            }
            $keyArr[] = [
                'day' => "DAY".($key+1)."：",
                'daytitle' => $daytitle,
                'day_key' => "day_".($key+1),
                'active' => $activeKeyArr,
                'day_description' => $value['day_description'],
            ];
            //经纬度
            $schedules[$key]['hasLine'] = false;
            $vo_start_poi=[];
            $vo_end_poi=[];
            $vo_ways_poi=[];
            $vo_latLng = [];
            if(count($value['child'])>=2 && $trip['show_day_map']==1){
                $vo_latLng = $value['child'];
                foreach ($vo_latLng as $v_key=>$v_poi){
                    //判断开始的类型
                    if(in_array($v_poi['activeType'],[1,4,15])){
                        $vo_latLng[$v_key]['lat'] = $v_poi['lat'];
                        $vo_latLng[$v_key]['lng'] = $v_poi['lng'];
                    }elseif(in_array($v_poi['activeType'],[2,3])){
                        $vo_latLng[$v_key]['lat'] = $v_poi['airport_lat'];
                        $vo_latLng[$v_key]['lng'] = $v_poi['airport_lng'];
                    }else{
                        $vo_latLng[$v_key]['lat'] = "";
                        $vo_latLng[$v_key]['lng'] = "";
                    }

                    if(empty($vo_latLng[$v_key]['lat']) || empty($vo_latLng[$v_key]['lng'])){
                        unset($vo_latLng[$v_key]);
                    }
                }
                $vo_start_poi=array_shift($vo_latLng);
                $vo_end_poi=array_pop($vo_latLng);

                if(!empty($vo_start_poi['lat']) && !empty($vo_start_poi['lng']) && !empty($vo_end_poi['lat']) && !empty($vo_end_poi['lng'])){
                    $schedules[$key]['hasLine'] = true;
                }else{
                    $schedules[$key]['hasLine'] = false;
                }
                foreach ($vo_latLng as $v_poi){
                    if(isset($v_poi['lat']) && isset($v_poi['lng']) && !empty($v_poi['lat']) && !empty($v_poi['lng'])){
                        $vo_ways_poi[] = ['lat'=>$v_poi['lat'],'lng'=>$v_poi['lng']];
                    }
                }
                $schedules[$key]['start_poi'] = json_encode($vo_start_poi);
                $schedules[$key]['end_poi'] = json_encode($vo_end_poi);
                $schedules[$key]['ways_poi'] = json_encode($vo_ways_poi);
            }
        }
        $admin=db('admin')->find($trip['adminid']);
        if(!empty($admin)){
            $trip['admin']=$admin['nickname'];
            $trip['wx_qrcode']=$admin['wx_qrcode'];
        }else{
            $trip['admin']="";
            $trip['wx_qrcode']="";
        }

        $current_url = url('admin/product/preview',['id'=>$id,'use_thumb'=>true]);
        $adminid= Cookie::get('admin');
        if(!empty($adminid)){
            $adminpwd=Db::name('admin')->where('id',$adminid)->select();
            $this->assign('url',$current_url.'?prevadminpwd='.$adminpwd[0]['password']);
            $this->assign('pageurl',$current_url.'?prevadminpwd='.$adminpwd[0]['password']);
            $this->assign('pwd',$adminpwd[0]['password']);
            $this->assign('wordurl',$current_url.'?prevadminpwd='.$adminpwd[0]['password']);
        }else{
            $prevadminpwd=$_GET['prevadminpwd'];
            $this->assign('url',$current_url);
            $this->assign('pwd',$prevadminpwd);
            $this->assign('wordurl',$current_url);
        }
        $baseurl = parse_url($current_url);
        $this->assign('baseurl',$baseurl['scheme'].'://'.$baseurl['host']);
        //检查是否为tob客户查看
        if(!empty($trip['tob_pdf'])){
            $trip['name'] = str_replace('快帮行','',$trip['name']);
        }
        $this->assign('name',$trip['name']);
        if(empty(array_filter($allcitys))) $allcitys[] = db('city')->field('name')->find($trip['start_city'])['name']??'';
        $this->assign('allcity',array_unique(array_filter($allcitys)));
        $this->assign('scheduletime',[$schedules[0]['time'],$schedules[count($schedules)-1]['time']]);
        if(!empty($trip['customer_content'])){
            $trip['customer_content'] = json_decode($trip['customer_content'],true);
        }
        $this->assign('trip',$trip);
        $this->assign('keyArr',$keyArr);
        $this->assign('schedules',$schedules);
        //判断城市地图是否绘制
        //开始城市经纬度
        $start_city = [];
        //结束城市经纬度
        $end_city = [];
        //中间城市经纬度
        $ways_city = [];
        $hasLine = false;
        if(count($allcityLatLngs)>=2 && $trip['show_city_map']==1){
            $hasLine  = true;
            $start_city = array_shift($allcityLatLngs);
            $end_city = array_pop($allcityLatLngs);
            $ways_city = $allcityLatLngs;
        }
        $hasLine = false;//关闭城市渲染
        $this->assign('hasLine',$hasLine);
        $this->assign('start_city',json_encode($start_city));
        $this->assign('end_city',json_encode($end_city));
        $this->assign('ways_city',json_encode($ways_city));

        $activeTypeList = (new TripApi())->getGlobalActiveTypeList(false);
        $this->assign('activeTypeList',$activeTypeList);
        $onlyShowDescOrderTypes = config('ONLY_SHOW_DESC_ORDER_TYPES');
        $onlyShowDescServiceTypeIds = db('service_type')->where(['type'=>['in',$onlyShowDescOrderTypes]])->column('id');
        $this->assign('onlyShowDescServiceTypeIds',$onlyShowDescServiceTypeIds);
        return $this->fetch();
    }

    //ajax查询POI 反选城市
    public function getpoiByInput(){
        $post = $this->request->post();
        $name = isset($post['input']) ? $post['input'] : '';
        $city_id = $post['city_id']??0;

        $where['deleted'] = 0;
        $classify = db('classify')->where(['is_use'=>1])->select();
        $typeids = array_column($classify,'classify_id');
        $where['typeid'] = ['in',$typeids];//1景点，3演出赛事，4限时活动，6其他，11美食
        if($name!==''){
            $where['name|eng_name'] = ['like','%'.$name.'%'];
        }else{
            $where['groupid'] = $city_id;
        }

        $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name,groupid")->select();

        return $poi;
    }

    //检索酒店名称
    //ajax查询POI 反选城市
    public function gethotelByInput(){
        $post = $this->request->post();
        $name = isset($post['input']) ? $post['input'] : '';
        $city_id = $post['city_id']??0;

        $where['deleted'] = 0;
        $where['typeid'] = ['in',5];//5酒店
        if($name!==''){
            $where['name|eng_name'] = ['like','%'.$name.'%'];
        }else{
            $where['groupid'] = $city_id;
        }

        $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name,groupid")->select();

        return $poi;
    }

    //获取交通类型 （用于订单系统核价）
    public function getTransportType($type_id)
    {
        $data =  [
            "1"=>"Transport_Vehicle_FromAirport",
            "2"=>"Transport_Vehicle_ToAirport",
            "8"=>"Transport_Vehicle_ShortDistance",
            "3"=>"Transport_Vehicle_HalfDay",
            "4"=>"Transport_Vehicle_OneDay",
            "5"=>"Transport_Vehicle_Around",
            "6"=>"Transport_Vehicle_LongTrip",
            "7"=>"self",
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }

    //获取交通类型 用于前端展示
    public function getTransportTitle($type_id = 0)
    {
        $data =  [
            "1"=>"接机",
            "2"=>"送机",
            "8"=>"单程接送",
            "3"=>"市区半日包车",
            "4"=>"市区一日包车",
            "5"=>"周边一日包车",
            "6"=>"长途包车"
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }

    //核价表格
    public function priceTable($trip_id=0){
        if($trip_id>0){
            $dayData = [];
            $num = 1;
            $weekArray=array("日","一","二","三","四","五","六");

            $hotelFlag = 0;
            $hotelNum = 1;
            $hotelShow = 1;
            $drive_num = 1;//判断连续几天
            $schedule = db("pschedule")->where("groupid",$trip_id)->order("displayorder asc")->select();
            if(!empty($schedule)){
                foreach ($schedule as $key=>$value) {
                    $day = [];
                    $active = db("pactive")->where("groupid",$value['id'])->order("displayorder asc")->select();

                    $day['day'] = "第".$num."天";
                    $day['time'] = $value['time'];
                    $day['title'] = $value['title'];
                    $day['transport_typeids'] = $value['transport_typeids'];
                    $day['week'] = "周".$weekArray[date("w",strtotime($value['time']))];

                    $cityArr = [];
                    $airportArr = [];
                    $activeText = '';
                    $hotel = '';
                    $hotel_id = '';
                    $hotel_time = [];
                    $hotel_key = 0;
                    if(!empty($active)){
                        foreach ($active as $k=>$v) {
                            if(!empty($v['cityname']) && $v['cityname']!=='' && !in_array($v['cityname'],$cityArr)){
                                $cityArr[] = $v['cityname'];
                            }

                            $textTitle = '';
                            if($v['activeType']==1){
                                $textTitle = "景点";
                            }elseif($v['activeType']==2){//接机
                                $airportArr[] = [
                                    'id'=>$v['poiid'],
                                    'text'=>"接机：".$v['poiname'],
                                    'typeText'=>'接机',
                                    'flight'=>$v['flight'],
                                ];
                                $textTitle = "接机";
                            }elseif($v['activeType']==3){//送机
                                $airportArr[] = [
                                    'id'=>$v['poiid'],
                                    'text'=>"送机：".$v['poiname'],
                                    'typeText'=>'送机',
                                    'flight'=>$v['flight'],
                                ];
                                $textTitle = "送机";
                            }elseif($v['activeType']==4){//酒店
                                $hotel = $v['poiname'];
                                $hotel_id = $v['poiid'];
                                $hotel_key = $k;
                                if(!in_array($value['time'],$hotel_time)){
                                    $hotel_time[] = $value['time'];
                                }
                                $textTitle = "酒店";
                            }elseif($v['activeType']==5){//特色体验
                                $textTitle = "特色体验";
                            }elseif($v['activeType']==6){//其他
                                $textTitle = "其他";
                            }

                            $textTitle = $textTitle." - ".$v['poiname'];

                            if(!empty($v['time']) && $v['time']!==0 && $v['time']!==''){
                                $textTitle = $v['time']." - ".$textTitle;
                            }

                            $activeText .= $textTitle."<br>";
                        }
                    }

                    $citys = implode(" - ",$cityArr);
                    $day['citys'] = $citys;

                    //合并相邻日期相同酒店
                    if($hotel_id>0 && $hotel_key>0){
                        if($hotelFlag==$hotel_id){
                            $dayData[$key-$hotelNum]['hotel_num'] = $hotelNum+1;
                            $dayData[$key-$hotelNum]['alldayhotel'] .= ",".$value['id'];
                            $dayData[$key-$hotelNum]['hotel_time'][] = $value['time'];
                            $hotelNum++;
                            $hotelShow = 0;
                        }else{
                            $hotelNum = 1;
                            $hotelShow = 1;
                            $dayData[$key]['alldayhotel'] = $value['id'];
                        }
                        $hotelFlag = $hotel_id;
                    }else{
                        $hotel_id = 0;
                        $hotelFlag = 0;
                        $hotelNum = 0;
                        $day['alldayhotel'] = '';
                    }

                    //判断当天是否存在自驾
                    if(!empty($value['transport_typeids'])){
                        $trifficArr = explode(",",$value['transport_typeids']);
                        if(in_array("7",$trifficArr)){//存在自驾
                            if(isset($dayData[$key-1]['drive_flag']) && $dayData[$key-1]['drive_flag']==1){
                                $dayData[$key-$drive_num]['alldaydrive'] .= ",".$value['id'];
                                $dayData[$key-$drive_num]['drive_num'] = $drive_num+1;
                                $dayData[$key-$drive_num]['drive_time'][] = $value['time'];
                                $drive_num++;
                                $day['drive_num'] = 0;
                            }else{
                                $drive_num = 1;
                                $day['drive_num'] = 1;
                                $day['drive_time'][] = $value['time'];
                                $day['alldaydrive'] = $value['id'];
                            }
                            $day['drive_flag'] = 1;
                        }else{
                            $drive_num = 1;
                            $day['drive_flag'] = 0;
                            $day['drive_num'] = 0;
                            $day['alldaydrive'] = $value['id'];
                        }
                    }else{
                        $drive_num = 1;
                        $day['drive_num'] = 0;
                        $day['alldaydrive'] = '';
                        $day['drive_flag'] = 0;
                    }

                    $day['id'] = $value['id'];
                    $day['airport'] = $airportArr;
                    $day['hotel_id'] = $hotel_id;
                    $day['hotel_num'] = $hotelNum;
                    $day['hotel_time'] = $hotel_time;
                    $day['hotel_show'] = $hotelShow;
                    $day['hotel'] = $hotel;
                    $day['activeText'] = $activeText;
                    $day['alldayhotel'] = $value['id'];

                    $dayData[$key] = $day;
                    $num++;
                }
            }

            return $dayData;
        }else{
            return [];
        }
    }

    //测试订单系统的包车核价
    public function getOrderSystemTransportData($id=604)
    {
        $post_data = $this->orderTransportApiData($id);
        //调用接口查询价格
        $KbxOther = new KbxOther();
        $priceData = $KbxOther->getCarPrice(['fullTravel'=>$post_data]);
//        var_dump($priceData);exit;
        $result = json_decode($priceData,true);
        //var_dump(json_encode(['fullTravel'=>$post_data]));exit;
//        var_dump(['fullTravel'=>$post_data]);exit;
//        var_dump($result);exit;
        $data = [];
        //记录拥有司导返程的日期
        if(!empty($result)){
            foreach ($result as $key=>$value){
                $a_data = [];
                $hasReturn = false;
                if(!empty($value['activities'])){
                    foreach ($value['activities'] as $a_value){
                        $displayString = $a_value['displayString']??"";
                        $a_data[] = [
                            "hasReturn"=>false,//默认没有司导返程
                            "serviceType"=>$a_value['serviceType']??"",
                            "displayString"=>$displayString,
                            "totalAmount"=>$a_value['totalAmount']??0,
                            "distance"=>$a_value['distance']??0,
                            "duration"=>$a_value['duration']??0,
                            "extra"=>$a_value['extra']??[],
                        ];
                        if($displayString=='司导返程'){
                            $hasReturn = true;
                        }
                    }
                }
                if(!empty($a_data) && $hasReturn){
                    foreach ($a_data as $a_key=>$a_value){
                        $a_data[$a_key]['hasReturn'] = true;
                    }
                }
                $data[] = [
                    'id'=>$value['id'],
                    'time'=>$value['time'],
                    'displayString'=>$value['displayString']??'',
                    'totalAmount'=>$value['totalAmount']??0,
                    'detail'=>$a_data,
                    'hasReturn'=>$hasReturn,
                ];
            }
        }
        return $data;
    }

    //交通核价接口封装
    //data是封装有active的schedule列表
    public function orderTransportApiData($id=604)
    {
        $trip = Db::name('trip')->where('id',$id)->find();
        //车型 默认是5座车 目前20座以上没有数据
        $carType = isset($trip['carType']) ? $trip['carType'] : 1;

        //$poiType = [1,4];//规定activeType去寻址poi
        //$airportType = [2,3];//规定activeType去寻址机场

        $resArr = [];
        $schedule = Db::name('pschedule')->where('groupid',$id)->order('displayorder')->select();

        if(!empty($schedule)){
            foreach ($schedule as $s_key=>$s_value){
                if(empty($s_value['transport_typeids'])){
                    $activities = [];
                }else{
                    $activities = [];
                    $active = Db::name('pactive')
                        ->alias('a')
                        ->join('city c','a.cityid=c.id','left')
                        ->join('poi p','a.poiid=p.id','left')
                        ->where('a.groupid',$s_value['id'])
                        ->field("a.*,c.kbx_id as cityId,c.lat,c.lng,p.lat as poi_lat,p.lng as poi_lng")
                        ->order('a.displayorder')->select();
                    if(empty($active)){
                        continue;
                    }
                    $trans_type_arr = explode(',',$s_value['transport_typeids']);
                    //sort($trans_type_arr);
                    $airportActive = [];
                    $airportActiveIndex = 0;

                    foreach ($trans_type_arr as $t_v){
                        $from = [];
                        $to = [];
                        $pois = [];
                        if($t_v==1){//交通 接机
                            foreach ($active as $a_k=>$a_v){
                                if($a_v['activeType']==2){//接机类型
                                    $airportActive = $a_v;
                                    $airportActiveIndex = $a_k;
                                    unset($active[$a_k]);
                                    break;
                                }
                            }
                            if(empty($airportActive)){
                                continue;
                            }
                            $from = [
                                'cityid'=>$airportActive['cityId'],
                                'placeId'=>$airportActive['poiid'],
                                'location'=>[
                                    'lat'=>$airportActive['airport_lat'],
                                    'lng'=>$airportActive['airport_lng'],
                                ],
                            ];
                            if(isset($active[$a_k+1]) && !empty($active[$a_k+1]['lat']) && !empty($active[$a_k+1]['lng'])){
                                $to = [
                                    'cityid'=>$airportActive['cityId'],
                                    'placeId'=>$airportActive['poiid'],
                                    'location'=>[
                                        'lat'=>$active[$a_k+1]['poi_lat'],
                                        'lng'=>$active[$a_k+1]['poi_lng'],
                                    ],
                                ];
                            }else{
                                $to = $from;
                            }
                        }elseif($t_v==2){//交通 送机
//                            $active = array_reverse($active);
                            foreach ($active as $a_k=>$a_v){
                                if($a_v['activeType']==3){//送机类型
                                    $airportActive = $a_v;
                                    $airportActiveIndex = $a_k;
                                    unset($active[$a_k]);
                                    break;
                                }
                            }
                            if(empty($airportActive)){
                                //还原数组
//                                $active = array_reverse($active);
                                continue;
                            }
                            $to = [
                                'cityid'=>$airportActive['cityId'],
                                'placeId'=>$airportActive['poiid'],
                                'location'=>[
                                    'lat'=>$airportActive['airport_lat'],
                                    'lng'=>$airportActive['airport_lng'],
                                ],
                            ];
                            if(isset($active[$a_k+1]) && !empty($active[$a_k+1]['lat']) && !empty($active[$a_k+1]['lng'])){
                                $from = [
                                    'cityid'=>$airportActive['cityId'],
                                    'placeId'=>$airportActive['poiid'],
                                    'location'=>[
                                        'lat'=>$active[$a_k+1]['poi_lat'],
                                        'lng'=>$active[$a_k+1]['poi_lng'],
                                    ],
                                ];
                            }else{
                                $from = $to;
                            }
                            //还原数组
                            //$active = array_reverse($active);
                        }
                        if(in_array($t_v,[1,2])){
                            if(empty($airportActive)){
                                continue;
                            }else{
                                $pois = [];
                                $activities[] = [
                                    'id'=>$airportActive['id'],
                                    'type'=>$this->getTransportType($t_v),
                                    'carType'=>$carType,
                                    'city'=>$airportActive['cityId'],
                                    'from'=>$from,
                                    'to'=>$to,
                                    'pois'=>$pois
                                ];
                                continue;
                            }
                        }
                        if(in_array($t_v,[3,4,5,6,8])){//交通类型 市内半日 市内一日 周边一日 长途
                            $validLatLng = [];
                            foreach ($active as $a_k=>$a_v){
                                //此类型包含 除其他以外的其他分类
                                //如果存在接送机 会通过以上步鄹移除机场poi
                                //若不存在接送机 机场poi也会计算到行程路线
                                if($a_v['activeType']!=6){
                                    //机场类型
                                    if(in_array($a_v['activeType'],[2,3]) && !empty($a_v['airport_lat']) && !empty($a_v['airport_lng'])){
                                        $a_v['lat'] = $a_v['airport_lat'];
                                        $a_v['lng'] = $a_v['airport_lng'];
                                        $validLatLng[] = $a_v;
                                    }elseif(!empty($a_v['poi_lat']) && !empty($a_v['poi_lat'])){
                                        $validLatLng[] = $a_v;
                                    }
                                }
                            }
                            if(empty($validLatLng)){
                                continue;
                            }else{
                                $start_poi = array_shift($validLatLng);
                                $from = [
                                    'cityid'=>$start_poi['cityId'],
                                    'location'=>[
                                        'lat'=>$start_poi['poi_lat'],
                                        'lng'=>$start_poi['poi_lng'],
                                    ],
                                ];
                                $pois = [];
                                if(count($validLatLng)>0){
                                    $end_poi = array_pop($validLatLng);
                                    $to = [
                                        'cityid'=>$end_poi['cityId'],
                                        'location'=>[
                                            'lat'=>$end_poi['poi_lat'],
                                            'lng'=>$end_poi['poi_lng'],
                                        ],
                                    ];
                                    if(count($validLatLng)>0){
                                        foreach ($validLatLng as $valid_k=>$valid_v){
                                            $pois[] = ['location'=>[
//                                                'title'=>$valid_v['poiname'],
                                                'lat'=>$valid_v['poi_lat'],
                                                'lng'=>$valid_v['poi_lng']
                                            ]];
                                        }
                                    }
                                }else{
                                    $to = $from;
                                }
                                $activities[] = [
                                    'id'=>$start_poi['id'],
                                    'type'=>$this->getTransportType($t_v),
                                    'carType'=>$carType,
                                    'city'=>$start_poi['cityId'],
                                    'from'=>$from,
                                    'to'=>$to,
                                    'pois'=>$pois
                                ];
                            }
                        }
                    }
                }

                $resArr[] = [
                    "id"=>$s_value['id'],
                    "time"=>$s_value['time'],
                    "fixed"=>$s_value['return_journey'],
                    "activities"=>$activities
                ];
            }
        }
//        return json_encode($resArr);exit;
        return $resArr;
    }

    public function packagePricingData($tripData,$transportData)
    {
        if(empty($tripData) || empty($transportData)){
            return $tripData;
        }
        //根据包车的数量判断总格子数
        $total_td_num = 0;
        foreach ($tripData as $key=>$value){
            //自驾
            $tripData[$key]['transport_pricing'] = [];
            $tripData[$key]['trans_count'] = 1;
            if(!empty($value['transport_typeids'])){
                $transport_ids = explode(",",$value['transport_typeids']);
                if(!empty($transport_ids)){
                    foreach($transportData as $k=>$v){
                        if($value['id']==$v['id']){
                            $transport_pricing = [];
                            $transport_pricing = array_merge($v['detail'],$transport_pricing);
                            $tripData[$key]['transport_pricing'] = $transport_pricing;
                            $tripData[$key]['trans_count'] = count($transport_pricing)>0?count($transport_pricing):1;
                            $total_td_num += $tripData[$key]['trans_count'];
                            break;
                        }
                    }
                }else{
                    continue;
                }
            }else{
                $total_td_num += 1;
            }

        }


        foreach ($tripData as $trans_k=>$trans_v){
            //每日格子数至少为1 当日没有包车则默认为1
            $tripData[$trans_k]['total_td_num'] = $total_td_num;
        }

        //匹配酒店 租车 和包车的单元格
        $index_time = array_column($tripData,"time");
        $time_index = array_flip(array_filter($index_time));
        foreach ($tripData as $t_key=>$t_value){
            //酒店单元格
            $tripData[$t_key]['hotel_td_num'] = 0;
            if($t_value['hotel_show']==1 && !empty($t_value['hotel_time'])){
                $count= count($t_value['hotel_time']);
                for ($i = 0;$i<$count;$i++){
                    if(isset($time_index[$t_value['hotel_time'][$i]])){
                        $tripData[$t_key]['hotel_td_num'] += $tripData[$time_index[$t_value['hotel_time'][$i]]]['trans_count'];
                    }
                }
            }
            $tripData[$t_key]['hotel_td_num'] = $tripData[$t_key]['hotel_td_num']>0?$tripData[$t_key]['hotel_td_num']:1;
            //租车单元格
            $tripData[$t_key]['drive_td_num'] = 0;
            if($t_value['drive_flag']==1 && !empty($t_value['drive_time'])){
                $count= count($t_value['drive_time']);
                for ($i = 0;$i<$count;$i++){
                    if(isset($time_index[$t_value['drive_time'][$i]])){
                        $tripData[$t_key]['drive_td_num'] += $tripData[$time_index[$t_value['drive_time'][$i]]]['trans_count'];
                    }
                }
            }
            $tripData[$t_key]['drive_td_num'] = $tripData[$t_key]['drive_td_num']>0?$tripData[$t_key]['drive_td_num']:1;
        }

        return $tripData;
    }

    //渲染数据表数据
    public function getTripPriceTableData($tripData){
        $schedule_ids = array_column($tripData,'id');
        if(!empty($schedule_ids)){
            $dayPrice = db("dayprice")->where(['groupid'=>['in',$schedule_ids]])->select();
            $schedule_index = array_flip($schedule_ids);
            if(!empty($dayPrice)){
                foreach ($dayPrice as $key=>$value){
                    $tableAirport = json_decode($value['airport_json'],true);
                    $tripAirport = $tripData[$schedule_index[$value['groupid']]]['airport'];

                    //机场匹配
                    foreach ($tripAirport as $air_key=>$air_value){
                        $tripAirport[$air_key]['detail'] = $tableAirport[$air_key][1]??"";
                        $tripAirport[$air_key]['price'] = $tableAirport[$air_key][2]??0;
                    }
                    $value['airportPrice'] = $tripAirport;
                    $tripData[$schedule_index[$value['groupid']]]['tableData'] = $value;
                    $tripData[$schedule_index[$value['groupid']]]['airport']=$tripAirport;
                }
            }
        }
        return $tripData;
    }

    //获取active两节点间距离
    public function getActiveDistance($num,$active){
        if($num<(count($active)-1)){
            $poi1 = [];
            $poi2 = [];
            $typeid1 = $active[$num]['activeType'];
            $typeid2 = $active[$num+1]['activeType'];

            if($typeid1==1 || $typeid1==4){// 1=POI  4=酒店
                $poiData= Db::name('poi')->where('id',$active[$num]['poiid'])->field('lat,lng')->find();
                $poi1['lat'] = $poiData['lat'];
                $poi1['lng'] = $poiData['lng'];
            }elseif($typeid1==2 || $typeid1=3){// 2=接机  3=送机
                $poi1['lat'] = $active[$num]['airport_lat'];
                $poi1['lng'] = $active[$num]['airport_lng'];
            }

            if($typeid2==1 || $typeid2==4){// 1=POI  4=酒店
                $poiData= Db::name('poi')->where('id',$active[$num+1]['poiid'])->field('lat,lng')->find();
                $poi2['lat'] = $poiData['lat'];
                $poi2['lng'] = $poiData['lng'];
            }elseif($typeid2==2 || $typeid2=3){// 2=接机  3=送机
                $poi2['lat'] = $active[$num+1]['airport_lat'];
                $poi2['lng'] = $active[$num+1]['airport_lng'];
            }

            if(isset($poi1['lat'])&&isset($poi1['lng'])&&isset($poi2['lat'])&&isset($poi2['lng'])){
                $limit = $this->getDistance($poi1['lat'],$poi1['lng'],$poi2['lat'],$poi2['lng']);
            }else{
                $limit=0;
            }

            return round($limit/1000,1);
        }else{
            return 0;
        }
    }

    //计算景点距离
    public function getDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

    //获取active详情用于修改active
    public function getActiveInfo(){
        $post = $this->request->post();
        $active_id = isset($post['active_id'])&&!empty($post['active_id'])?$post['active_id']:0;
        $active = db("pactive")->find($active_id);

        if(empty($active)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }else{
            $poi = db("poi")->where("id",$active['poiid'])->field("introduce,thumb")->find();
            //当POI简介不存在时，去POI表中获取补录
            if(empty($active['poi_content'])){
                $introduce = $poi['introduce'];
                if(!empty($introduce)){
                    $pactiveModel = new pactiveModel();
                    $pactiveModel->allowField(true)->save(['poi_content'=>$introduce],['id'=>$active_id]);
                    $active['poi_content'] = $introduce;
                }
            }

            $poiImg_arr = array_values(array_filter(explode(",",$active['poiImg'])));
            $other_images_arr = array_values(array_filter(explode(",",$active['other_images'])));
            // 默认不推荐用户poi图片 2019-06-06
            //$thumb = array_values(array_filter(explode(",",$poi['thumb'])));
            //$poiImg_arr = array_merge($poiImg_arr,$thumb);
//            $p_arr = [];
//            $o_arr = [];
//            $p_arr[] = array_shift($poiImg_arr);
//            $p_arr[] = array_shift($poiImg_arr);
//            $o_arr[] = array_shift($other_images_arr);
//            $o_arr[] = array_shift($other_images_arr);
            $active['poiImg_arr'] = array_filter($poiImg_arr);
            $active['other_images_arr'] = array_filter($other_images_arr);
            return json(['code'=>200,"msg"=>'获取成功','data'=>$active]);
        }
    }

    //配置页面
    public function productConfig()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("product")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        if(request()->isPost()){
            $post = request()->post();
            if(!empty($post)){
                $config_arr = ['showmobile','showticket','showopen_time','showticket_url','showeng_introduce','showdescription','showprice','showthumb','showsource','showaddress','showgrade','show_day_map','show_city_map','showcontent','showpoicontent','showcareful','showback','showintroduction','showpricedetail'];

                foreach ($post as $key=>$value){
                    if(in_array($key,$config_arr) && $value=='on'){
                        $post[$key] = 1;
                    }
                }
                foreach ($config_arr as $value){
                    if(!isset($post[$value]) || $post[$value]!=1){
                        $post[$value] = 0;
                    }
                }

                $post['sale_starttime'] = !empty($post['sale_starttime'])?strtotime(date("Y").'-'.$post['sale_starttime']):0;
                $post['sale_endtime'] = !empty($post['sale_endtime'])?strtotime(date("Y").'-'.$post['sale_endtime']):0;

                $adminid = Cookie::get('admin');
                $post['update_admin'] = $adminid;
                $post['update_time'] = time();

                $model = new ProductModel();
                $res = $model->allowField(true)->where(['id'=>$id])->update($post);
                if($res!==false){
                    return $this->success("修改成功");
                }else{
                    return $this->error("修改失败");
                }
            }else{
                return $this->error("修改失败");
            }
        }

        //供应商   不能放上面，引入类构造方法会过滤html标签
        list($supplier,$supplierNameArr) = $this->getSupplierList();
        $this->assign('supplier',$supplier);

        $trip['sale_starttime'] = !empty($trip['sale_starttime'])?date("m-d",$trip['sale_starttime']):0;
        $trip['sale_endtime'] = !empty($trip['sale_endtime'])?date("m-d",$trip['sale_endtime']):0;
            $this->assign('trip',$trip);
        return $this->fetch();
    }

    //定制页面导入行程
    public function productimport()
    {
        if($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post();

            //导入行程id串
            if(!empty($post['tripids'])){
                $tripids = $post['tripids'];
                $tripsArr = explode(",",$tripids);
            }else{
                $tripsArr = [];
            }

            if(!empty($post['productids'])){
                $productids = $post['productids'];
                $productsArr = explode(",",$productids);
            }else{
                $productsArr = [];
            }

            if(empty($tripsArr) && empty($productsArr)){
                return $this->error("至少要选择一个行程导入！");
            }

            if(empty($post['trip_id'])){
                return $this->error("导入失败！");
            }else{
                $tripInfo = db("product")->find($post['trip_id']);
                if(empty($tripInfo)){
                    return $this->error("行程有误！");
                }
            }
            $tripid = $post['trip_id'];
            $scheduleList = db("pschedule")->field("id,time,displayorder")->where(['groupid'=>$tripInfo['id']])->order("displayorder asc")->select();
            $days = count($scheduleList);
            $schedulenum = $days+1;
            $res = $this->importProductByTripIds($tripsArr,$productsArr,$tripid,$days,$schedulenum);
            if($res){
                return $this->success('导入成功',"",$tripid);
            }else{
                return $this->error('导入失败');
            }
        }else{
            $where['type'] = "CITY";
            $where['deleted'] = 0;
            $city = db("city")->where($where)->field("id,name")->select();
            $cityJson = json_encode($city,JSON_UNESCAPED_UNICODE);
            $this->assign('cityJson',$cityJson);

            //供应商   不能放上面，引入类构造方法会过滤html标签
            $KbxOther = new KbxOther();
            list($supplier,$supplierNameArr) = $this->getSupplierList();
            $this->assign('supplier',$supplier);

            return $this->fetch();
        }
    }

    //查看每日地图
    public function getDayMap()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $ajax = $this->request->has('ajax') ? $this->request->param('ajax', 0, 'intval') : 0;
        if($id>0){
            $schedule = db("pschedule")->find($id);
            $hasLine = false;
            $map['start_poi'] = [];
            $map['end_poi'] = [];
            $map['middle_poi'] = [];
            if(!empty($schedule)){
                $active = db("pactive a")
                    ->field("a.id,a.activeType,a.poiname,p.name,p.eng_name,p.lat,p.lng,a.airport_lat,a.airport_lng")
                    ->join("poi p","p.id=a.poiid",'left')
                    ->where(['a.groupid'=>$id])
                    ->order("a.displayorder asc")
                    ->select();
                //将经纬度转换成float类型
                foreach ($active as $key=>$value){
                    if(in_array($value['activeType'],[1,4,15,16,17,18,19])){
                        $value['lat'] = floatval($value['lat']);
                        $value['lng'] = floatval($value['lng']);
                    }elseif(in_array($value['activeType'],[2,3])){
                        $value['lat'] = floatval($value['airport_lat']);
                        $value['lng'] = floatval($value['airport_lng']);
                        $active[$key]['name'] = $value['poiname']??$value['name'];
                    }else{
                        $value['lat'] = 0;
                        $value['lat'] = 0;
                    }

                    if(empty($value['lat']) || empty($value['lng'])){
                        unset($active[$key]);
                    }else{
                        $active[$key]['lat'] = floatval($value['lat']);
                        $active[$key]['lng'] = floatval($value['lng']);
                    }
                }
                if(count($active)>=2){
                    $hasLine = true;
                    $map['start_poi'] = array_shift($active);
                    $map['end_poi'] = array_pop($active);
                    $map['middle_poi'] = $active;
                }
            }
        }
        if(!empty($ajax)){
            return json(['code'=>200,'msg'=>'获取成功','data'=>['map'=>$map,'hasLine'=>$hasLine]]);exit;
        }else{
            $this->assign("map",$map);
            $this->assign("hasLine",$hasLine);
            return $this->fetch();
        }
    }

    //ajax获取ActiveData  替代getpoi
    public function getActiveData(){
        $post = $this->request->post();
        $type_id = $post['type_id'];//类型
        $active_id = $post['active_id'];
        $city_id = $post['city_id'];

        $updateData = [];
        $resData = [];
        if($type_id==1){//POI
            $where['deleted'] = 0;
            $where['groupid'] = $city_id;
            $where['typeid'] = ['in',[1,2,3,4,6]];//1景点，3演出赛事，4限时活动，6其他，11美食
            $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
            $resData = $poi;
        }elseif($type_id==2 || $type_id==3){//2接机  3送机
            $airportData = $this->kbxGetAirport($city_id);
            $airport = [];
            foreach ($airportData as $k=>$v) {
                $airportName = (isset($v['nameen']) && $v['nameen']!=='') ? $v['name']."(".$v['nameen'].")" : $v['name'];
                $airport[] = ['id'=>$v['id'],'name'=>$airportName];
            }
            $resData = $airport;
        }elseif($type_id==4){//酒店
            $where['deleted'] = 0;
            $where['groupid'] = $city_id;
            $where['typeid'] = 5;
            $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
            $resData = $poi;
        }elseif($type_id==6){//其他

        }elseif($type_id>10){
            $where['deleted'] = 0;
            $where['groupid'] = $city_id;
            $where['typeid'] = $type_id;
            $poi = db("poi")->where($where)->field("id,concat(name,'(',eng_name,')') as name")->select();
            $resData = $poi;
        }
        $city = db("city")->where("id",$city_id)->field("name")->find();

        $updateData["cityid"] = $city_id;
        $updateData["cityname"] = $city['name'];
        $updateData["activeType"] = $type_id;
        $updateData["poiid"] = 0;
        $updateData["poiname"] = '';
        $updateData["poi_content"] = '';
        $updateData["content"] = '';

        $pactiveModel = new pactiveModel();
        $pactiveModel->allowField(true)->save($updateData,['id'=>$active_id]);

        $trip = db("product")
            ->alias("t")
            ->join('pschedule s','s.groupid=t.id')
            ->join('active a','s.id=a.groupid')
            ->where("a.id",$active_id)
            ->field("t.id")
            ->find();
        //统计城市
        $this->countCity($trip['id']);

        return $resData;
    }

    //选择POI保存
    public function setpoi(){
        $post = $this->request->post();
        $active_id = $post['active_id'];

        $poiData = [];
        if(!empty($post['poiid']) && $post['poiid']>0){
            $poiid = $post['poiid'];
            $poi = db("poi")
                ->alias("p")
                ->join('city c','p.groupid=c.id',"left")
                ->where("p.id",$poiid)
                ->field("p.name,p.eng_name,p.groupid,p.typeid,p.introduce,p.thumb,c.name as cityname")
                ->find();
            $groupid = $poi['groupid'];
            $poiData['poiid'] = $poiid;
            $poiData['cityname'] = $poi['cityname'];
            $poiData['cityid'] = $poi['groupid'];
            $poiData['poitype'] = $poi['typeid'];
            $poiData['poi_content'] = $poi['introduce'];
            $poiData['poiImg'] = $poi['thumb'];
            $poiData['showthumb'] = 1;
            if(!empty($poi['eng_name']) && $poi['eng_name']!==''){
                $poiData['poiname'] = $poi['name']."（".$poi['eng_name']."）";
            }else{
                $poiData['poiname'] = $poi['name'];
            }
        }else{
            $poiData['poiid'] = '';
            $poiData['poitype'] = '';
            $poiData['poiname'] = '';
            $groupid = '';
        }

        $poiData['title'] = $poiData['poiname'];

        $pactiveModel = new pactiveModel();
        if(false == $pactiveModel->allowField(true)->save($poiData,["id"=>$active_id])) {
            return $this->error('修改失败');
        } else {
            return $this->success('修改成功','',['groupid'=>$groupid]);
        }
    }

    //选择active 保存   替代setpoi
    public function setActive(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $type_id = $post['type_id'];//类型

        $activeData = [];
        $activeData['poiid'] = '';
        $activeData['poitype'] = '';
        $activeData['poiname'] = '';
        $groupid = '';
        $typeid = '';
        if(!empty($post['item_id']) && $post['item_id']>0){
            $global_active_type_arr = $this->getGlobalActiveTypeList();
            if(in_array($type_id,$global_active_type_arr)){//1=POI，5=酒店
                $poiid = $post['item_id'];
                $poi = db("poi")
                    ->alias("p")
                    ->join('city c','p.groupid=c.id',"left")
                    ->where("p.id",$poiid)
                    ->field("p.name,p.eng_name,p.groupid,p.typeid,p.introduce,p.thumb,c.name as cityname")
                    ->find();
                $groupid = $poi['groupid'];
                if(in_array($poi['typeid'],[1,2,3,4,6])){
                    $typeid = 1;
                }elseif($poi['typeid']==5){
                    $typeid = 4;
                }else{
                    $typeid = $poi['typeid'];
                }
                $activeData['poiid'] = $poiid;
                $activeData['cityname'] = $poi['cityname'];
                $activeData['cityid'] = $poi['groupid'];
                $activeData['poitype'] = $poi['typeid'];
                $activeData['activeType'] = $typeid;
                $activeData['poi_content'] = $poi['introduce'];
                $activeData['content'] = '';
                $activeData['poiImg'] = implode(',',array_slice(array_filter(explode(',',$poi['thumb'])),0,2));
                $activeData['showthumb'] = 1;
                if(!empty($poi['eng_name']) && $poi['eng_name']!==''){
                    $activeData['poiname'] = $poi['name']."（".$poi['eng_name']."）";
                }else{
                    $activeData['poiname'] = $poi['name'];
                }
            }elseif($type_id==2 || $type_id==3){//接机  送机
                $activeArr = db("pactive")->where("id",$active_id)->field("cityid")->find();
                $airportData = $this->kbxGetAirport($activeArr['cityid']);
                foreach ($airportData as $k=>$v) {
                    if($v['id']==$post['item_id']){
                        $activeData['airport_lat'] = $v['location']['lat'];
                        $activeData['airport_lng'] = $v['location']['lng'];
                    }
                }
                $activeData['poiid'] = $post['item_id'];
                $activeData['poiname'] = $post['item_text'];
                $activeData['content'] = '';
                $activeData['poi_content'] = '';
                $activeData['airport_lnglat'] = $post['item_text'];
            }
        }

        $activeData['title'] = $activeData['poiname'];

        $pactiveModel = new pactiveModel();
        if(false == $pactiveModel->allowField(true)->save($activeData,["id"=>$active_id])) {
            return $this->error('修改失败');
        } else {
            return $this->success('修改成功','',['groupid'=>$groupid,'typeid'=>$typeid]);
        }
    }

    //ajax修改schedule标题
    public function changeTitle(){
        $post = $this->request->post();
        $schedule_id = $post['schedule_id'];
        $title = $post['title'];

        if(false == db('pschedule')->where('id', $schedule_id)->update(['title' =>$title])) {
            return $this->error('修改失败');
        }else{
            return $this->success('修改成功');
        }
    }

    //拖拽排序页面
    public function dragsort(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if($id > 0) {
            $tripid = $id;
            $schedule = db("pschedule")->where("groupid",$id)->order("displayorder asc")->field("id,title,time")->select();
            foreach ($schedule as $k=>$v) {
                $active = db("pactive")
                    ->where("groupid",$v['id'])
                    ->order("displayorder asc")
                    ->field("id,poiname,title")
                    ->select();

                foreach ($active as $a_k=>$a_v) {
                    $active[$a_k]['poiname'] = $a_v['poiname']=='' ? $a_v['title'] : $a_v['poiname'];
                }

                $schedule[$k]['active'] = $active;
            }
            foreach ($schedule as $key=> $value){
                $schedule[$key]['dayNum'] = $key+1;
            }

            $this->assign('schedule',$schedule);
        }else{
            $schedule = [];
            $tripid = 0;
        }
        $this->assign('schedule',$schedule);
        $this->assign('tripid',$tripid);

        return $this->fetch();
    }

    //更新每日行程中的地图
    public function updateEveryDayPOIMapImg()
    {
        $post = $this->request->post();
        $trip_id = isset($post['trip_id'])&&!empty($post['trip_id'])?$post['trip_id']:0;
        if(empty($trip_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $schedule = db("pschedule")->where("groupid",$trip_id)->select();
        if(empty($schedule)){
            return json(['code'=>-1,"msg"=>'请先添加日程']);
        }else{
            $schedule_ids = array_column($schedule,"id");
            $active = db("pactive a")
                ->field("a.id,a.groupid,a.poiid,p.lat,p.lng")
                ->join("poi p","p.id=a.poiid","left")
                ->where(['a.groupid'=>['in',$schedule_ids]])
                ->order("a.displayorder asc")//获取poi的正确顺序
                ->select();
            foreach ($schedule as $key=>$value){
                $schedule[$key]['poilist'] = [];
                foreach ($active as $k=>$v){
                    //未选择poi需要过滤
                    if($value['id']==$v['groupid'] && !empty($v['poiid'])){
                        $schedule[$key]['poilist'][] = $v;
                    }
                }
            }
            db::startTrans();
            try{
                //更新每个日程的线路图
                foreach ($schedule as $key=>$value){
                    $thumb_map_img = "";
                    if(!empty($value['poilist'])){
                        $thumb_map_img = (new GoogleMap())->getGoogleMapImgByRoad($value['poilist'],500,300);
                    }
                    db("pschedule")->where("id",$value['id'])->update(['thumb_map_img'=>$thumb_map_img]);
                }
                db::commit();
                return json(['code'=>200,'msg'=>"更新成功"]);
            }catch (Exception $e){
                db::rollback();
                return json(['code'=>-1,'msg'=>"更新失败"]);
            }
        }
    }

    //更新信息
    public function changeInfo(){
        if($this->request->isPost()) {
            //是提交操作changeInfo
            $post = $this->request->post();
            if(empty($post['tripid']) || $post['tripid']<=0){
                return $this->error("请求错误，缺少tripid");
            }
            $tripInfo = db('product')->find($post['tripid']);
            if(empty($tripInfo)){
                return $this->error(Lang::get('获取产品失败'));
            }
            //code码必须唯一
            if(!empty($post['item_num'])){
                $isExistCode = db("product")->where(['item_num'=>$post['item_num'],'id'=>['neq',$post['tripid']]])->count();
                if($isExistCode>0){
                    return $this->error("产品编码已存在,请更换");
                }
            }
            if(!empty($post['driver_id'])){//采购方式 司导id
                $post['supplier_id'] = '';
                $post['supplier_item_code'] = '';
            }else{
                $post['driver_id'] = '';
            }
            $sale_time = !empty($post['sale_time'])?explode(' - ',$post['sale_time']):[];
            //$post['sale_starttime'] = !empty($sale_time[0])?strtotime($sale_time[0]):'';
            //$post['sale_endtime'] = !empty($sale_time[1])?strtotime($sale_time[1]):'';
            if(!empty($_POST['sale_details'])){
                $post['sale_details'] = (new Common())->replaceWxImageUrl($_POST['sale_details']);
                $post['sale_details'] = (new Common())->replaceWxSectionLabel($post['sale_details']);
            }
            $adminid = Cookie::get('admin');
            $post['update_admin'] = $adminid;
            $post['update_time'] = time();
            $model=new ProductModel();
            $productInfo = db('product')->find($post['tripid']);
            $serviceType = $post['service_type']??'';
            if(!empty($serviceType)){
                $orderType = db('service_type')->find($serviceType)['type']??'';
            }else{
                $orderType = '';
            }
            if(isset($post['subTitle'])) $post['product_sub_title'] = $post['subTitle']??'';
            unset($post['customer_content']);//去除更多条款
            if(false == $model->allowField(true)->save($post,['id'=>$post['tripid']])) {
                return $this->error('修改失败');
            } else {
                if(!empty($post['service_type']) && $post['service_type']==18){
                    $this->saveProductElectronic($post['tripid'],$post);
                }
                $goodsData = db("goods")->where("goods_tcode",$post['item_num'])->find();
                if(!empty($goodsData)){
                    //更新商品表数据
                    $updateGoodsData = [];
                    $updateGoodsData['price_include'] = str_replace("\r\n",'<br>',$post['price']);
                    if(isset($post['priceno'])) $updateGoodsData['price_noinclude'] = str_replace("\r\n",'<br>',$post['priceno']);
                    $updateGoodsData['goods_retreating'] = str_replace("\r\n",'<br>',$post['back']);
                    $updateGoodsData['goods_careful'] = str_replace("\r\n",'<br>',$post['careful']);
                    if(isset($post['sale_details'])) $updateGoodsData['goods_introduce'] = $post['sale_details'];
                    $updateGoodsData['starttime'] = $tripInfo['sale_starttime'];
                    $updateGoodsData['endtime'] = $tripInfo['sale_endtime'];
                    if(isset($post['goods_image'])){
                        $updateGoodsData['goods_image'] = $post['goods_image'];
                        $updateGoodsData['small_image'] = $post['goods_image'];
                    }
                    if(isset($post['goods_video'])) $updateGoodsData['goods_video'] = $post['goods_video'];
                    $updateGoodsData['tag_id'] = $post['tag_id'];
                    $updateGoodsData['updatetime'] = time();
                    $updateGoodsData['need_confirm'] = $post['need_confirm']??0;
                    $updateGoodsData['orderType'] = $orderType;
                    $resGoods = db("goods")->where("goods_tcode",$post['item_num'])->update($updateGoodsData);
                    if($resGoods===false){
                        return $this->error('goods表修改失败');
                    }
                    //更新标品数据
                    $standardtrip = db('standardtrip')->where('trip_id',$post['tripid'])->find();
                    if(!empty($standardtrip)){

                        $updStandardData = [];
                        $updStandardData['startCityId'] = $post['start_city']??0;
                        $updStandardData['days'] = $productInfo['days']??1;
//                        $updStandardData['endDays'] = $post['endDays']??3;
                        $resStandard = db('standardtrip')->where('trip_id',$post['tripid'])->update($updStandardData);
                        if($resStandard===false){
                            return $this->error('standardtrip'.Lang::get('修改失败'));
                        }

                        //更新标品数据
                        $standard = db('standard')->where('id',$standardtrip['sid'])->find();
                        if(!empty($standard)){
                            $updStandard = [];
                            if(!empty($post['name'])){
                                $updStandard['name'] = $post['name'];
                            }
                            $updStandard['type'] = $orderType=='Vehicle'?1:2;
                            $updStandard['allow_everyone_quote'] = $post['allow_everyone_quote']??0;
                            $updStandard['is_group_exhibition'] = $post['is_group_exhibition']??0;
                            if(isset($post['subTitle'])) $updStandard['introduce'] = $post['subTitle']??'';
//                            $updStandard['s_endDays'] = $post['endDays']??3;
                            $resStandard = db('standard')->where('id',$standardtrip['sid'])->update($updStandard);
                            if($resStandard===false){
                                return $this->error('standard'.Lang::get('修改失败'));
                            }else{
                                //通用产品修改为自营 下架ES
                                if($updStandard['allow_everyone_quote'] < 1){
                                    //es 删除该商品
                                    (new Esapi())->delStandardDoc($standardtrip['sid']);
                                }else{
                                    //es 更新该商品
                                    (new Esapi())->refreshStandardDataToES($standardtrip['sid']);
                                }
                            }
                        }

                    }
                }
                //增加操作日志
                (new Common())->createProductOperationLog([
                    'product_id'=>$post['tripid'],
                    'admin_type'=>1,
                    'admin_id'=>Cookie::get('admin'),
                    'operate_url'=>$this->request->path(),
                    'operate_body'=>json_encode($this->request->post())
                ]);
                return $this->success('修改成功');
            }
        } else {
            return $this->error('没有数据');
        }
    }

    //非提交方式更新产品信息
    public function ajaxUpdateProductInfo()
    {
        $post = request()->post();
        $id = $post['id']??0;
        if(empty($id)) return $this->error('请求参数错误');
        $product = db('product')->find($id);
        if(empty($product)) return $this->error('产品信息错误');
        if(!empty($_POST['sale_details'])){

            $post['sale_details'] = (new Common())->replaceWxImageUrl($_POST['sale_details']);;
            $post['sale_details'] = (new Common())->replaceWxSectionLabel($post['sale_details']);;
        }
        if(!empty($_POST['text_plan'])){

            $post['text_plan'] = (new Common())->replaceWxImageUrl($_POST['text_plan']);
            $post['text_plan'] = (new Common())->replaceWxSectionLabel($post['text_plan']);
        }
        //设置允许自动更新的字段
        $allow_field = [
            'sale_starttime',
            'sale_endtime',
            'ota_price_out',
            'ota_price_busy',
            'cost_price_out',
            'cost_price_busy',
            'price',
            'priceno',
            'back',
            'careful',
            'introduction',
            'sale_details',
            'saletime_more',
            'reservation',
            'people_detail',
            'start_person_num',
            'total_person_num',
            'description',
            'group_type',
            'currency',
            'net_weight',
            'shelf_life',
            'production_date',
            'production_license',
            'executive_standard_no',
            'storage_conditions',
            'edible_methods',
            'text_plan',
            'assembling_place',
            'activity_duration',
            'activity_person_num',
            'play_ways',
            'self_driving_level',
            'vehicle_require',
            'itinerary_summary',
            'self_driving_distance',
            'customer_info_config',
            'all_customer_req',
        ];
        if(!empty($post['sale_starttime'])) $post['sale_starttime'] = strtotime($post['sale_starttime']);
        if(!empty($post['sale_endtime'])) $post['sale_endtime'] = strtotime($post['sale_endtime']);
        unset($post['id']);
        foreach ($post as $key=>$value){
            if(!in_array($key,$allow_field)) return $this->error('不允许自动更新'.$key.'的内容');
        }

        $res = db('product')->where('id',$id)->update($post);

        if($res!==false){
            if(!empty($post['service_type']) && $post['service_type']==18){
                $this->saveProductElectronic($id,$post);
            }
            $goodsData = db("goods")->where("goods_tcode",$product['item_num'])->find();
            if(!empty($goodsData) && !empty($product['item_num'])){
                //更新商品表数据
                $updateGoodsData = [];
                if(!empty($post['price'])) $updateGoodsData['price_include'] = str_replace("\r\n",'<br>',$post['price']);
                if(!empty($post['priceno'])) $updateGoodsData['price_noinclude'] = str_replace("\r\n",'<br>',$post['priceno']);
                if(!empty($post['back'])) $updateGoodsData['goods_retreating'] = str_replace("\r\n",'<br>',$post['back']);
                if(!empty($post['careful'])) $updateGoodsData['goods_careful'] = str_replace("\r\n",'<br>',$post['careful']);
                if(!empty($post['sale_details'])) $updateGoodsData['goods_introduce'] = $post['sale_details'];
                if(!empty($post['sale_starttime'])) $updateGoodsData['starttime'] = $post['sale_starttime'];
                if(!empty($post['sale_endtime'])) $updateGoodsData['endtime'] = $post['sale_endtime'];
                $updateGoodsData['updatetime'] = time();
                $resGoods = db("goods")->where("goods_tcode",$product['item_num'])->update($updateGoodsData);
                if($resGoods===false){
                    return $this->error('goods表修改失败');
                }
            }

            //增加操作日志
            (new Common())->createProductOperationLog([
                'product_id'=>$id,
                'admin_type'=>1,
                'admin_id'=>Cookie::get('admin'),
                'operate_url'=>$this->request->path(),
                'operate_body'=>json_encode($this->request->post())
            ]);

            return $this->success('已更新');
        }else{
            return $this->error('更新失败');
        }

    }

    //更新每日行程中的地图是否显示
    public function changeShowScheduleMapImg()
    {
        $post = $this->request->post();
        $trip_id = isset($post['trip_id'])&&!empty($post['trip_id'])?$post['trip_id']:0;
        if(empty($trip_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $is_show = isset($post['is_show'])&&$post['is_show']==1?1:0;
        $res = db("product")->where("id",$trip_id)->update(['show_day_map'=>$is_show]);

        if($res!==false){
            return json(['code'=>200,"msg"=>'更新成功']);
        }else{
            return json(['code'=>-1,"msg"=>'更新失败']);
        }
    }

    //更新行程中的总地图是否显示
    public function changeShowCityMapImg()
    {
        $post = $this->request->post();
        $trip_id = isset($post['trip_id'])&&!empty($post['trip_id'])?$post['trip_id']:0;
        if(empty($trip_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $is_show = isset($post['is_show'])&&$post['is_show']==1?1:0;
        $res = db("product")->where("id",$trip_id)->update(['show_city_map'=>$is_show]);
        if($res!==false){
            return json(['code'=>200,"msg"=>'更新成功']);
        }else{
            return json(['code'=>-1,"msg"=>'更新失败']);
        }
    }

    //更新节点详细数据
    public function updateActiveInfo(){
        $post = $this->request->post();
        $active_id = isset($post['active_id'])&&!empty($post['active_id'])?$post['active_id']:0;
        $active = db("pactive")->find($active_id);
        if(empty($active)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $pactiveModel = new pactiveModel();
        if(isset($post['title']) && $active['activeType']==6){
            $post['poiname'] = $post['title'];
            $post['poiImg'] = '';
        }
        if(!empty($_POST['content'])) $post['content'] = $_POST['content'];
        if(!empty($_POST['poi_content'])) $post['poi_content'] = $_POST['poi_content'];
        //单独设置自费
        unset($post['own_fee']);
        if(false == $pactiveModel->allowField(true)->save($post,["id"=>$active_id])) {
            return $this->error('保存失败');
        } else {
            return $this->success('保存成功','');
        }
    }

    //快速定制推荐POI列表
    public function getRecommendPoiList()
    {
        $post = $this->request->post();
        $poi_id = isset($post['poi_id'])&&!empty($post['poi_id'])?$post['poi_id']:0;
        if(empty($poi_id)){
            return json(['code'=>-1,"msg"=>'请求错误']);
        }
        $model = new PModel();
        $poilist = $model->getNearbyPOI($poi_id,50000);
        //获取城市名称
        if(!empty($poilist)){
            $cityids = array_column($poilist,"groupid");
            $cityList = db("city")->where(['id'=>['in',$cityids]])->select();
            foreach ($poilist as $key=>$value){
                $poilist[$key]['cityId'] = 0;
                $poilist[$key]['cityName'] = '';
                foreach ($cityList as $k=>$v){
                    if($value['groupid']==$v['id']){
                        $poilist[$key]['cityName'] = $v['name'];
                        $poilist[$key]['cityId'] = $v['id'];
                    }
                }
            }
        }
        return json(['code'=>200,'msg'=>"获取列表成功","data"=>$poilist]);
    }

    //ajax  获取节点前后  一共三个节点的距离
    public function getPointDistance(){
        if(request()->isPost()) {
            $post = request()->post();
            $groupid = $post['groupid'];
            $active_id = $post['active_id'];
            if(empty($groupid) || empty($active_id)){
                return $this->error('无法获取距离');
            }

            $active = db("pactive")
                ->where("groupid",$groupid)
                ->order("displayorder asc")
                ->field("id,poiid,activeType,airport_lat,airport_lng")
                ->select();

            //获取距离
            $disArr = [];
            foreach ($active as $k=>$v) {
                if($v['id']==$active_id){
                    $disArr[] = [
                        'id'=>$active[$k]['id'],
                        'distance'=>$this->getActiveDistance($k,$active)
                    ];

                    if($k==0){
                        if(count($active)>1){
                            $disArr[] = [
                                'id'=>$active[$k+1]['id'],
                                'distance'=>$this->getActiveDistance($k+1,$active)
                            ];
                        }
                    }elseif($k==count($active)-1){
                        $disArr[] = [
                            'id'=>$active[$k-1]['id'],
                            'distance'=>$this->getActiveDistance($k-1,$active)
                        ];
                    }else{
                        $disArr[] = [
                            'id'=>$active[$k-1]['id'],
                            'distance'=>$this->getActiveDistance($k-1,$active)
                        ];
                        $disArr[] = [
                            'id'=>$active[$k+1]['id'],
                            'distance'=>$this->getActiveDistance($k+1,$active)
                        ];
                    }
                }
            }

            return $disArr;
        }else{
            return $this->error('获取距离失败');
        }
    }

    //修改每日交通类型
    public function updTransportType()
    {
        $post = request()->post();
        $schedule_id = isset($post['schedule_id'])?$post['schedule_id']:0;
        $upd_type = isset($post['upd_type'])?$post['upd_type']:"update";
        $schedule = db("pschedule")->find($schedule_id);
        if(empty($schedule)){
            $this->error("日程错误");exit;
        }else{
            $res= db("pschedule")->where(['id'=>$schedule_id])->update(['transport_typeids'=>$post{'day_type'}]);
            if($res){
                if($upd_type=='delete'){
                    $this->success("删除成功");
                }else{
                    $this->success("修改成功");
                }
            }else{
                $this->error("修改失败");
            }
        }
    }

    //修改价格
    public function changePriceTable(){
        $post = request()->post();
        $schedule_id = $post['schedule_id'];
        $type = $post['type'];
        $data = $post['data'];
        $name = isset($post['name']) ? $post['name'] : '';

        $model = new DaypriceModel();

        if(empty($schedule_id)){
            return $this->error("缺少id");
        }
        if($name==''){
            return $this->error("缺少name");
        }

        $priceData = db("dayprice")->where("groupid",$schedule_id)->find();
        if(empty($priceData)){//不存在时新增
            db('dayprice')->insert(['groupid'=>$schedule_id]);
        }

        $whereArr = ['groupid'=>$schedule_id];
        $updateData = [];
        if($type=='airport'){//航班信息
            $updateData[$name] = json_encode($data,JSON_UNESCAPED_UNICODE);
            $model->allowField(true)->save($updateData,$whereArr);
        }elseif($type=='hotel'){//酒店信息
            $alldayhotel = $post['alldayhotel'];
            $dayArr = explode(",",$alldayhotel);
            $updateData[$name] = $data;
            if($name=='hotelDetail'){
                foreach ($dayArr as $k=>$v) {
                    if(false==db("dayprice")->where("groupid",$v)->find()){//不存在时新增
                        $updateData['groupid'] = $v;
                        $model->allowField(true)->insert($updateData);
                    }else{
                        $whereArr = ['groupid'=>$v];
                        $model->allowField(true)->save($updateData,$whereArr);
                    }
                }
            }else{
                $model->allowField(true)->save($updateData,$whereArr);
            }
        }elseif($type=='drive'){//租车信息
            $alldaydrive = $post['alldaydrive'];
            $dayArr = explode(",",$alldaydrive);
            $updateData[$name] = $data;
            if($name=='driveDetail'){
                foreach ($dayArr as $k=>$v) {
                    if(false==db("dayprice")->where("groupid",$v)->find()){//不存在时新增
                        $updateData['groupid'] = $v;
                        $model->allowField(true)->insert($updateData);
                    }else{
                        $whereArr = ['groupid'=>$v];
                        $model->allowField(true)->save($updateData,$whereArr);
                    }
                }
            }else{
                $model->allowField(true)->save($updateData,$whereArr);
            }
        }elseif($type=='other') {//其他信息
            $updateData[$name] = $data;
            if($name=='insurancePrice' || $name=='insuranceDetail'){
                $schedule = db("pschedule")->where("id",$schedule_id)->field("groupid")->find();
                $tripid = $schedule['groupid'];

                $productModel = new ProductModel();
                $productModel->allowField(true)->save($updateData,['id'=>$tripid]);
            }else{
                $model->allowField(true)->save($updateData,$whereArr);
            }
        }

        return $this->success("修改成功");
    }

    //保存总价
    public function saveTotalPrice(){
        $post = request()->post();
        $tripid = $post['tripid'];
        $totalPrice = $post['total_price'];

        $trip = db("trip")->where("id",$tripid)->field("total_price")->find();

        if($trip['total_price']!==$totalPrice && $totalPrice>0){
            $model = new ProductModel();
            unset($post['tripid']);
            $adminid = Cookie::get('admin');
            $post['update_admin'] = $adminid;
            $post['update_time'] = time();
            if(false==$model->allowField(true)->save($post,['id'=>$tripid])){
                return $this->error("保存总价失败");
            }else{
                return $this->success("修改成功");
            }
        }else{
            return $this->success("修改成功");
        }
    }

    //更新司导返程配置
    public function updReturnJourney()
    {
        $post = request()->post();
        $day_id = $post['day_id'];
        $status = $post['status'];

        $res = db("pschedule")->where(['id'=>$day_id])->update(['return_journey'=>$status]);
        if($res!==false){
            if($status==2){
                $this->success("新增司导返程成功");
            }else{
                $this->success("删除司导返程成功");
            }
        }else{
            $this->error("设置失败");
        }
    }

    //导入实现
    private function importProductByTripIds($tripsArr,$productsArr,$tripid,$days=0,$schedulenum=1)
    {
        $model = new ProductModel();
        Db::startTrans(); //启动事务
        try {
            $nowtime = time();
            if(!empty($tripsArr)){
                foreach ($tripsArr as $key=>$value){
                    $getschedule= Db::name("schedule")->where(['groupid' => $value])->order("displayorder asc")->select();
                    $days+=count($getschedule);
                    foreach ($getschedule as $k=>$v) {
                        $tempnowscheduleid = $v['id'];
                        unset($v['id']);
                        unset($v['day_description']);
                        $v['groupid'] = $tripid;
                        $v['displayorder'] = $schedulenum;
                        $schedulenum+=1;
                        $v['create_time'] = $nowtime;
                        $v['update_time'] = $nowtime;

                        //插入日程数据
                        Db::name('pschedule')->insert($v);
                        $newscheduleid=Db::name('pschedule')->getLastInsID();
                        if ($newscheduleid) {
                            $getactive= Db::name("active")->where(['groupid' => $tempnowscheduleid])->order("displayorder asc")->select();
                            foreach ($getactive as $m=>$n) {
                                //typeid弃用   by Suley  2019-08-21
                                    if(!empty($n['poiid']) && is_numeric($n['poiid'])==true){
                                        $poi = db("poi")->where("id",$n['poiid'])->find();
                                        if($poi['deleted']==1){
                                            continue;
                                        }


                                        $n['poiname'] = !empty($poi['name'])?$poi['name']:$n['poiname'];
                                    }
                                    $n['other_images'] = '';
//                                if($n['typeid']==1 && !in_array($n['activeType'],[2,3])){//机场
//                                    $n['activeType'] = $n['portType']=='Transport_Vehicle_ToAirport' ? 3 :2;//接送机类型
//                                    $n['poiid'] = !empty($n['airportPlace'])?$n['airportPlace']:'';//机场ID
//                                    $n['other_images'] = '';
//                                    $n['title'] = "";
//
//                                    if($n['poiid']!=='' && !empty($n['cityid'])){
//                                        $airportData = $this->kbxGetAirport($n['cityid']);
//                                        foreach ($airportData as $k=>$v) {
//                                            if($v['id']==$n['poiid']){
//                                                $n['poiname'] = (isset($v['nameen']) && $v['nameen']!=='') ? $v['name']."(".$v['nameen'].")" : $v['name'];
//                                                $n['airport_lat'] = $v['location']['lat'];
//                                                $n['airport_lng'] = $v['location']['lng'];
//                                                $n['title'] = $n['poiname'];
//                                            }
//                                        }
//                                    }
//                                }elseif($n['typeid']==4){//其他
//                                    $n['activeType'] = 6;
//                                    $n['poiname'] = !empty($n['poiname'])?$n['poiname']:$n['title'];
//                                }else{
//                                    if(!empty($n['poiid']) && is_numeric($n['poiid'])==true){
//                                        $poi = db("poi")->where("id",$n['poiid'])->find();
//                                        if($poi['deleted']==1){
//                                            continue;
//                                        }
//
//                                        if($poi['typeid']==5){//酒店
//                                            $n['activeType'] = 4;
//                                        }
//
//                                        $n['poiname'] = !empty($poi['name'])?$poi['name']:$n['poiname'];
//                                    }
//                                    $n['other_images'] = '';
//                                }

                                $n['showthumb'] = 1;
                                $n['groupid'] = $newscheduleid;
                                $n['create_time'] = $nowtime;
                                $n['update_time'] = $nowtime;
                                $n['time'] = "";

                                //插入日程数据
                                unset($n['id']);
                                Db::name('pactive')->insert($n);
                            }
                        }
                    }
                }
            }
            if(!empty($productsArr)){
                foreach ($productsArr as $key=>$value){
                    $getschedule= Db::name("pschedule")->where(['groupid' => $value])->order("displayorder asc")->select();
                    $days+=count($getschedule);
                    foreach ($getschedule as $k=>$v) {
                        $tempnowscheduleid = $v['id'];
                        unset($v['id']);
                        $v['groupid'] = $tripid;
                        $v['displayorder'] = $schedulenum;
                        $schedulenum+=1;
                        $v['create_time'] = $nowtime;
                        $v['update_time'] = $nowtime;

                        //插入日程数据
                        Db::name('pschedule')->insert($v);
                        $newscheduleid=Db::name('pschedule')->getLastInsID();

                        if ($newscheduleid) {
                            $getactive= Db::name("pactive")->where(['groupid' => $tempnowscheduleid])->order("displayorder asc")->select();
                            foreach ($getactive as $m=>$n) {
                                //typeid弃用   by Suley  2019-08-21
                                    if(!empty($n['poiid']) && is_numeric($n['poiid'])==true){
                                        $poi = db("poi")->where("id",$n['poiid'])->find();
                                        if($poi['deleted']==1){
                                            continue;
                                        }


                                        $n['poiname'] = !empty($poi['name'])?$poi['name']:$n['poiname'];
                                    }
                                    $n['other_images'] = '';
//                                if($n['typeid']==1 && !in_array($n['activeType'],[2,3])){//机场
//                                    $n['activeType'] = $n['portType']=='Transport_Vehicle_ToAirport' ? 3 :2;//接送机类型
//                                    $n['poiid'] = !empty($n['airportPlace'])?$n['airportPlace']:'';//机场ID
//                                    $n['other_images'] = '';
//                                    $n['title'] = "";
//
//                                    if($n['poiid']!=='' && !empty($n['cityid'])){
//                                        $airportData = $this->kbxGetAirport($n['cityid']);
//                                        foreach ($airportData as $k=>$v) {
//                                            if($v['id']==$n['poiid']){
//                                                $n['poiname'] = (isset($v['nameen']) && $v['nameen']!=='') ? $v['name']."(".$v['nameen'].")" : $v['name'];
//                                                $n['airport_lat'] = $v['location']['lat'];
//                                                $n['airport_lng'] = $v['location']['lng'];
//                                                $n['title'] = $n['poiname'];
//                                            }
//                                        }
//                                    }
//                                }elseif($n['typeid']==4){//其他
//                                    $n['activeType'] = 6;
//                                    $n['poiname'] = !empty($n['poiname'])?$n['poiname']:$n['title'];
//                                }else{
//                                    if(!empty($n['poiid']) && is_numeric($n['poiid'])==true){
//                                        $poi = db("poi")->where("id",$n['poiid'])->find();
//                                        if($poi['deleted']==1){
//                                            continue;
//                                        }
//
//                                        if($poi['typeid']==5){//酒店
//                                            $n['activeType'] = 4;
//                                        }
//
//                                        $n['poiname'] = !empty($poi['name'])?$poi['name']:$n['poiname'];
//                                    }
//                                    $n['other_images'] = '';
//                                }

                                $n['showthumb'] = 1;
                                $n['groupid'] = $newscheduleid;
                                $n['create_time'] = $nowtime;
                                $n['update_time'] = $nowtime;
                                $n['time'] = "";

                                //插入日程数据
                                unset($n['id']);
                                unset($n['own_fee']);
                                Db::name('pactive')->insert($n);
                            }
                        }
                    }
                }
            }
            $update_data['days']=$days;
            $adminid = Cookie::get('admin');
            $update_data['update_admin'] = $adminid;
            $update_data['update_time'] = time();
            $model->allowField(true)->save($update_data,['id'=>$tripid]);
            $this->countCity($tripid);
            Db::commit(); //提交事务
            return true;
        } catch (Exception $e) {
            Db::rollback(); //回滚事务
            return false;
        }
    }

    //统计trip内城市
    public function countCity($trip_id){
        if(empty($trip_id) || $trip_id<=0){
            return false;
        }
        $cityArr = [];
        $include_city = "";
        $cityCounts = 0;
        $firstCity = 0;
        $schedule = db("pschedule")->where("groupid",$trip_id)->select();
        if(!empty($schedule)){
            $schedule_ids = array_column($schedule,"id");
            if(!empty($schedule_ids)){
                $cityid_arr = db("pactive a")
                    ->join("pschedule s","s.id=a.groupid","left")
                    ->where(["a.groupid"=>['in',$schedule_ids]])
                    ->field("a.cityid")
                    ->order("s.displayorder asc,a.displayorder asc")//获取poi的正确顺序
                    ->select();
                if(!empty($cityid_arr)){
                    $cityArr = array_column($cityid_arr,"cityid");
                    $include_city = implode(",",$cityArr);

                    $cityUniqueArr = array_unique($cityArr);
                    $cityCounts = count($cityUniqueArr);
                    $cityList = array_values($cityArr);
                    $firstCity = $cityList[0];
                }
            }
        }

        $tripInfo = db("product")->find($trip_id);
        if($include_city!=$tripInfo['include_city']){
            $thumb_map_img = "";
            if(!empty($cityArr)){
                //获取所有城市的经纬度
                $cityLatLng = db("city")->field("id,lat,lng")->where(['id'=>['in',$cityArr]])->select();
                //如果所有城市都是一个城市，不需要生成地图图片
                if(count($cityLatLng)>1){
                    $map_city = [];
                    foreach ($cityArr as $key=>$value){
                        foreach ($cityLatLng as $k=>$v){
                            $last_latLng = end($map_city);
                            if($value==$v['id'] && $last_latLng !=$v && !empty($v['lat']) && !empty($v['lng'])){
                                $map_city[] = $v;
                            }
                        }
                    }
                    if(!empty($map_city)){
                        //$thumb_map_img = (new GoogleMap())->getGoogleMapImgByRoad($map_city,500,300);
                    }
                }
            }
            //更新包含城市和路线地图
            db("product")->where("id",$trip_id)->update(['citys'=>$cityCounts,'start_city'=>$firstCity,'include_city'=>$include_city,'thumb_map_img'=>$thumb_map_img]);
        }

        return true;
    }

    //ajax增加一个active
    public function addActive(){
        $post = $this->request->post();
        $schedule_id = $post['schedule_id'];
        $activeType = !empty($post['activeType']) ? $post['activeType'] : 1;
        $cityid = !empty($post['cityid']) ? $post['cityid'] : 0;
        $nowtime = time();
        $active = db("pactive")->where("groupid",$schedule_id)->order("displayorder desc")->find();

        if(!empty($active)){
            $displayorder = $active['displayorder']+1;
        }else{
            $displayorder = 1;
        }

        //添加active
        $activeData = [];

        $activeData['activeType'] = $activeType;
        if($activeType==1){//1POI，2接机，3送机，4酒店，5特色体验，6其他
            $activeData['typeid'] = 3;//1机场，2城市，3POI，5跟团游，6商品，4其他',
        }elseif($activeType==2 || $activeType==3){
            $activeData['typeid'] = 1;
        }elseif($activeType==4){
            $activeData['typeid'] = 3;
        }elseif($activeType==6){
            $activeData['typeid'] = 4;
        }else{
            $activeData['typeid'] = 5;
        }

        $activeData['groupid'] = $schedule_id;
        if($cityid>0){
            $activeData['cityid'] = $cityid;
        }
        $activeData['displayorder'] = $displayorder;
        $activeData['create_time'] = $nowtime;
        $activeData['update_time'] = $nowtime;

        $activeModel = new pactiveModel();
        if(false == $activeModel->allowField(true)->create($activeData)) {
            return $this->error('插入失败');
        } else {
            $activeid = Db::name('pactive')->getLastInsID();
            return $this->success("插入成功","",$activeid);
        }
    }

    //ajax删除POI
    public function deletePoi(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $active = db("pactive")->where("id",$active_id)->find();

        $trip = db("product")
            ->alias("t")
            ->join('pschedule s','s.groupid=t.id')
            ->join('pactive a','s.id=a.groupid')
            ->where("a.id",$active_id)
            ->field("t.id")
            ->find();

        if(!empty($active)){
            if(false == db("pactive")->where('id',$active_id)->delete()) {
                return $this->error('删除失败');
            } else {
                //统计城市
                $this->countCity($trip['id']);

                return $this->success('删除成功');
            }
        }
    }

    //ajax增加天数
    public function addDay(){
        $post = $this->request->post();
        $tripid = $post['tripid'];
        $nowtime = time();

        $days = db("pschedule")->where("groupid",$tripid)->count("id");
        $days = $days+1;
        $updateData['days'] = $days;

        $adminid = Cookie::get('admin');
        $update_data['update_admin'] = $adminid;
        $update_data['update_time'] = time();
        $productModel = new ProductModel();

        if(false == $productModel->allowField(true)->save($updateData,['id'=>$tripid])) {
            return $this->error('新增失败');
        } else {
            $schedule = db("pschedule")->where("groupid",$tripid)->order("displayorder desc")->find();
            $scheduleModel = new pscheduleModel();
            $daysData = [];
            $daysData['groupid'] = $tripid;
            $daysData['time'] = date("Y-m-d",strtotime("+1 day",strtotime($schedule['time'])));
            $daysData['displayorder'] = $schedule['displayorder']+1;
            $daysData['create_time'] = $nowtime;
            $daysData['update_time'] = $nowtime;
            $scheduleModel->allowField(true)->create($daysData);
            $schedule_id = Db::name('schedule')->getLastInsID();

            //添加active
            $activeData = [];
            $activeData['typeid'] = 3;
            $activeData['groupid'] = $schedule_id;
            $activeData['displayorder'] = 1;
            $activeData['create_time'] = $nowtime;
            $activeData['update_time'] = $nowtime;
            $activeModel = new pactiveModel();
            $activeModel->allowField(true)->create($activeData);
            $active_id = Db::name('active')->getLastInsID();

            $where_city['type'] = "CITY";
            $where_city['deleted'] = 0;

            $city = db("city")->where($where_city)->field("id,name")->select();

            $resData = [
                'days'=>$days,
                'schedule_id'=>$schedule_id,
                'active_id'=>$active_id,
                'displayorder'=>$daysData['displayorder'],
                'time'=>$daysData['time'],
                'city'=>$city
            ];

            return $this->success("新增成功","",$resData);
        }
    }

    //ajax删除天
    public function deleteDay(){
        $post = $this->request->post();
        $schedule_id = $post['schedule_id'];
        $schedule = db("pschedule")->where("id",$schedule_id)->field("id,groupid")->find();
        $trip = db('product')->where('id', $schedule['groupid'])->find();

        $date = date("Y-m-d",$trip['start_go_time']);
        $days = db("pschedule")->where("groupid",$schedule['groupid'])->count("id");
        $days = $days-1;
        if($days>0){
            db('product')->where('id', $schedule['groupid'])->update(['days' =>$days]);
            if(!empty($schedule)){
                $active = db("pactive")->where('groupid',$schedule_id)->find();
                if(!empty($active)){
                    if(false == db("pactive")->where('groupid',$schedule_id)->delete()) {
                        return $this->error('删除失败');
                    }
                }
                if(false == db("pschedule")->where('id',$schedule_id)->delete()) {
                    return $this->error('删除失败');
                } else {
                    //重新排序日期
                    $new_schedule = db("pschedule")->where("groupid",$schedule['groupid'])->order("displayorder asc")->select();
                    $num = 1;
                    foreach ($new_schedule as $k=>$v) {
                        db('pschedule')->where('id', $v['id'])->update(['time' =>$date,'displayorder'=>$num]);
                        $num++;
                        $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));
                    }

                    //统计城市
                    $this->countCity($trip['id']);

                    return $this->success('删除成功');
                }
            }
        }else{
            return $this->error('至少要有一日行程！');
        }
    }

    //ajax拖拽修改排序
    public function changeDrag(){
        $post = $this->request->post();
        $type = $post['type'];// 1为day  2为poi
        if($type==1){//修改Day排序
            $tripid = $post['tripid'];
            $schedule_id_str = $post['days_str'];
            $schedule_id_Arr = explode(",",$schedule_id_str);
            $schedule_id_Arr = array_filter($schedule_id_Arr);
            $num = 1;

            $trip = db('product')->where('id', $tripid)->field("start_go_time")->find();
            $date = date("Y-m-d",$trip['start_go_time']);

            foreach ($schedule_id_Arr as $k=>$v) {
                $schedule_id = $v;
                db('pschedule')->where('id', $schedule_id)->update(['displayorder' =>$num,'time'=>$date]);
                $num++;
                $date = date("Y-m-d",strtotime("+1 day",strtotime($date)));
            }
            //统计城市 刷新城市地图
            $this->countCity($tripid);

            return $this->success('排序成功');
        }elseif($type==2){//修改poi排序
            $active_id = $post['active_id'];
            $schedule_id = $post['schedule_id'];
            $active_id_str = $post['actives_str'];
            $active_id_Arr = explode(",",$active_id_str);
            $active_id_Arr = array_filter($active_id_Arr);
            $num = 1;
            $trip = db("pschedule")->field("groupid")->where("id",$schedule_id)->find();
            db('pactive')->where('id', $active_id)->update(['groupid' =>$schedule_id]);
            foreach ($active_id_Arr as $k=>$v) {
                db('pactive')->where('id',$v)->update(['displayorder' =>$num]);
                $num++;
            }
            //统计城市 刷新城市地图
            $this->countCity($trip['groupid']);
            return $this->success('排序成功');
        }else{
            return $this->error('排序失败');
        }
    }

    //获取可导入的行程列表
    public function getTripForImport(){
        $post = $this->request->post();

        $where = [];
        if(!empty($post['title'])){
            $title = $post['title'];
            $where['id|name'] = ['like','%'.$title.'%'];
        }
        //查询产品
        $trip1 = db("trip")->where($where)->field("id,use_type,name,days,people,include_city")->select();
        //查询定制
        $trip2 = db("product")->where($where)->field("id,use_type,name,days,people,include_city")->select();
        $trip = $trip1+$trip2;

        $res_trip = [];
        if(!empty($post['citys'])){
            $city_str = $post['citys'];
            $city_arr = explode(",",$city_str);
            $city_arr = array_filter($city_arr);
            foreach ($trip as $k=>$v) {
                $flag = 1;
                $include_city = $v['include_city'];
                if(!empty($include_city) && $include_city!==''){
                    $include_city_arr = explode(",",$include_city);
                    foreach ($city_arr as $city) {
                        if(!in_array($city,$include_city_arr)){
                            $flag = 0;
                            break;
                        }
                    }
                }else{
                    continue;
                }

                if($flag==1){
                    $res_trip[] = $v;
                }
            }
        }else{
            $res_trip = $trip;
        }

        return $res_trip;
    }

    //获取机场
    public function kbxGetAirport($city_id)
    {
        $data = [];
        if(isset($city_id) && $city_id>0){
            $city = db("city")->where("id",$city_id)->field("kbx_id")->find();
            $kbxToken = new KbxToken();
            $url = $kbxToken->url.'/cities/'.$city['kbx_id'].'/airports';
            $token = 'Bearer ' . $kbxToken->kbxToken();
            $res = $kbxToken->get_data($url, $token);
            $data = $kbxToken->object_array($res);
        }

        return $data;
    }

    //单独设置自费
    public function setProductActiveOwnFee()
    {
        $post = request()->post();
        if(isset($post['own_fee']) && isset($post['id'])){
            $res = db::name("pactive")->where(['id'=>$post['id']])->update(['own_fee'=>$post['own_fee']]);
            if($res!==false){
                $this->success("设置成功");
            }else{
                $this->error("设置失败");
            }
        }else{
            $this->error("设置失败");
        }
    }

    //是否更换司导
    public function changeDirector()
    {
        $post = request()->post();

        if(!empty($post['id']) && isset($post['value'])){
            $res = db::name('pschedule')->where(['id'=>$post['id']])->update(['replace_director'=>$post['value']]);
            if($res!=false){
                $this->success('修改成功');
            }else{
                $this->error("修改成功");
            }
        }else{
            $this->error("修改失败");
        }
    }

    //ajax 获取司导信息
    public function getDriverData(){
        $post = request()->post();
        if(empty($post['name'])){
            return false;
        }
        $KbxOther = new KbxOther();
        $data = $KbxOther->getDriverByTel($post['name']);
        return $data;
    }

    //*****************交通类型***************************
    public function traffic()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("product")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        $schedules = Db::name('pschedule')->field("id,displayorder,time,groupid")->where('groupid',$id)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('pactive a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->field("a.id,a.displayorder,a.title,a.poiname,a.groupid")
                ->where(['a.groupid' => ['in', $schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }else{
            return $this->error('请先添加节点');
        }
        $trip_index_arr = [];
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    $schedules[$key]['children'][] = $v;
                    //计算节点个数
                    $trip_index_arr[] = $key.'-'.(count($schedules[$key]['children'])-1);
                }
            }
        }
        $transport_json = json_decode($trip['transport_json'],true);
        $transport_json = !empty($transport_json)?$transport_json:[];
        if(!empty($transport_json)){
            $transport_arr = $this->deconstructTransJson($transport_json,$trip_index_arr);
            foreach ($schedules as $key=>$value){
                foreach ($value['children'] as $child_key=>$child_value){
                    if(in_array($key.'-'.$child_key,$transport_arr)){
                        $schedules[$key]['disabled'] = true;
                        $schedules[$key]['children'][$child_key]['disabled'] = true;
                    }
                }
            }
        }
        $this->assign('trip',$trip);
        $this->assign('transport',$this->getTransportTitle());
        $this->assign("schedules",$schedules);
        //展示交通列表
        $transList = $this->getDaysByTransJson($transport_json,$schedules);
        $this->assign("transList",$transList);
        return $this->fetch();
    }
    //批量创建交通
    public function createMoreTransport()
    {
        $post = request()->post();
        if(!empty($post)){
            $trip_id = isset($post['trip_id'])?$post['trip_id']:0;
            $index = isset($post['index'])?$post['index']:"";
            $trans_type = isset($post['trans_type'])?$post['trans_type']:0;
            $days = isset($post['days'])?$post['days']:[];
            $items = isset($post['items'])?$post['items']:[];
            $trip = db("product")->find($trip_id);
            if(empty($trip)){
                $this->error("行程信息有误");exit;
            }
            if(!in_array($trans_type,[1,2,3,4,5,6,8]) || empty($days) || empty($items)){
                $this->error("参数信息有误");exit;
            }
            $transItem = [];
//            if(in_array($trans_type,[1,2])){
//                foreach ($items as $value){
//                    $transItem[] = [
//                        'type'=>$trans_type,
//                        'start'=>$value,
//                        'end'=>$value
//                    ];
//                }
//            }elseif(in_array($trans_type,[3,4,5])){
//                foreach ($days as $value){
//                    $itemData = [];
//                    foreach ($items as $v){
//                        if(strpos($v,$value."-")!==false){
//                            $itemData[] = $v;
//                        }
//                    }
//                    if(empty($itemData)){
//                        continue;
//                    }
//                    sort($itemData);
//                    reset($itemData);
//                    $start = current($itemData);
//                    $end = end($itemData);
//                    $transItem[] = [
//                        'type'=>$trans_type,
//                        'start'=>$start,
//                        'end'=>$end
//                    ];
//                }
//
//            }elseif(in_array($trans_type,[6,8])){
//                reset($items);
//                $start = current($items);
//                $end = end($items);
//                $transItem[] = [
//                    'type'=>$trans_type,
//                    'start'=>$start,
//                    'end'=>$end
//                ];
//            }
            //修改任何类型随意设置节点 2019 08 06
            reset($items);
            $start = current($items);
            $end = end($items);
            $transItem[] = [
                'type'=>$trans_type,
                'start'=>$start,
                'end'=>$end
            ];
            //对项目进行排序
            $_json = json_decode($trip['section_trans_json'],true);
            $_json[$index] = $_json[$index]??[];
            $_json[$index] = array_merge($_json[$index],$transItem);
            $trans_json = json_encode($_json);
            $res = db("product")->where(['id'=>$trip_id])->update(['section_trans_json'=>$trans_json]);
            if($res!==false){
                $this->success("保存成功","",$transItem);
            }else{
                $this->error("保存失败");
            }
        }else{
            $this->error("请求错误");exit;
        }
    }
    //解构transportJson数据
    public function deconstructTransJson($json_arr,$trip_arr){
        $data = [];
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_index = array_search($value['start'],$trip_arr);
                $e_index = array_search($value['end'],$trip_arr);
                if($s_index<$e_index){
                    $section_data = array_slice($trip_arr,$s_index,$e_index-$s_index+1);
                    $data = array_merge($data,$section_data);
                }else{
                    $data[] = $trip_arr[$s_index];
                }
            }
        }
        return $data;
    }
    //解构sectionJson数据
    public function deconstructSectionJson($json_arr,$trip_arr){
        $data = [];
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_index = array_search($value['start'],$trip_arr);
                $e_index = array_search($value['end'],$trip_arr);
                if($s_index<$e_index){
                    $section_data = array_slice($trip_arr,$s_index,$e_index-$s_index+1);
                    $data = array_merge($data,$section_data);
                }else{
                    $data[] = $trip_arr[$s_index];
                }
            }
        }
        return $data;
    }
    //获取天数的标签
    public function getDaysByTransJson($json_arr,$actives)
    {
        if(empty($json_arr)){
            return [];
        }else{
            foreach ($json_arr as $key=>$value){
                $s_day = explode("-",$value['start'])[0];
                $e_day = explode("-",$value['end'])[0];
                $s_poi = explode("-",$value['start'])[1];
                $e_poi = explode("-",$value['end'])[1];
                $json_arr[$key]['s_day'] = intval($s_day);
                $json_arr[$key]['e_day'] = intval($e_day);
                $s_label = $actives[$s_day]['children'][$s_poi]['label'];
                $e_label = $actives[$e_day]['children'][$e_poi]['label'];
                if($s_label==$e_label){
                    $json_arr[$key]['s_poiname'] = '/';
                }else{
                    $json_arr[$key]['s_poiname'] = $s_label;
                }
                $json_arr[$key]['e_poiname'] = $e_label ;
                if($s_day==$e_day){
                    $json_arr[$key]['day_title'] ='第'.($s_day+1).'天';
                }else{
                    $json_arr[$key]['day_title'] ='第'.($s_day+1).'天至第'.($e_day+1).'天';
                }
                $json_arr[$key]['type_title'] =$this->getTransportTitle($value['type']);
            }
        }
        $sday_arr = array_column($json_arr,"s_day");
        $eday_arr = array_column($json_arr,"e_day");
        array_multisort($sday_arr,SORT_ASC,$eday_arr,SORT_ASC,$json_arr);
        return $json_arr;
    }
    //删除包车类型的设置
    public function delTransport()
    {
        $post = request()->post();
        $index = $post['index']??"";
        if(empty($post['id']) || $post['key']<0 || $index==""){
            $this->error("删除失败");
        }
        $product = db("product")->find($post['id']);
        if(empty($product)){
            $this->error("产品信息不存在");
        }
        if(empty($product['section_trans_json'])){
            $this->error("暂未配置行程");
        }
        $transport_json = json_decode($product['section_trans_json'],true);
        unset($transport_json[$index][$post['key']]);
        //如果当前段不存在包车 则删除当前设置
        if(empty($transport_json[$index])){
            unset($transport_json[$index]);
            //判断如果分段行程内的包车类型为空，则更新分段的包车类型
            $section_json = json_decode($product['section_json'],true);
            $section_json[$index]['transport'] = 0;
            $section_json = json_encode($section_json);
            db("product")->where(['id'=>$post['id']])->update(['section_json'=>$section_json]);
        }else{
            $transport_json[$index] = array_values($transport_json[$index]);
        }
        $transport_json = json_encode($transport_json);
        $res = db("product")->where(['id'=>$post['id']])->update(['section_trans_json'=>$transport_json]);
        if($res!==false){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }
    //ajax 拖拽active保存新groupid
    public function changeActiveDay(){
        $post = $this->request->post();
        $active_id = intval($post['active_id']);
        $schedule_id = intval($post['schedule_id']);
        $active_id_list = $post['active_id_list'];
        $where['id'] = $active_id;
        $pactiveModel = new pactiveModel();
        $active = $pactiveModel->where($where)->field("groupid")->find();
        $groupid = intval($active['groupid']);
        $activeData = $pactiveModel->where('groupid',$groupid)->field("id")->order("displayorder asc")->select();
        $prev_id = 0;
        $next_id = 0;
        //查询原节点前后节点id
        foreach ($activeData as $k=>$v) {
            if($v['id']==$active_id){
                if($k>0){
                    $prev_id = $activeData[$k-1]['id'];
                }
                if($k<(count($activeData)-1)){
                    $next_id = $activeData[$k+1]['id'];
                }
            }
        }
        $error = false;
        if($groupid!==$schedule_id){
            //修改变动节点的父id
            $res = $pactiveModel->where($where)->update(['groupid'=>$schedule_id]);
            if(false==$res){
                $error = true;
            }
        }
        //排序
        $active_id_Arr = explode(",",$active_id_list);
        $active_id_Arr = array_filter($active_id_Arr);
        $num = 1;
        foreach ($active_id_Arr as $k=>$v) {
            db("pactive")->where("id",$v)->update(['displayorder'=>$num]);
            $num++;
        }
        if($error){
            return $this->error("修改失败");
        }else{
            return $this->success("修改成功",'',['prev_id'=>$prev_id,'next_id'=>$next_id]);
        }
    }
    //保存每日的简要说明
    public function saveDayDescription()
    {
        $post = request()->post();
        $sid = $post['schedule_id']??0;
        $value = $post['value']??'';
        $pschedule = db('pschedule')->find($sid);
        if(empty($sid) || empty($pschedule)) return $this->error(Lang::get('错误'));

        $res = db('pschedule')->where(['id'=>$sid])->update(['day_description'=>$value]);
        if($res!==false){
            return $this->success(Lang::get('保存成功'));
        }else{
            return $this->error(Lang::get('保存失败'));
        }
    }
    //上传附件
    public function savefile()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $typeid = $this->request->has('typeid') ? $this->request->param('typeid', 0, 'intval') : 2;
        $trip = db("product")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        if(request()->isPost()){
            $post = request()->post();
            if(!empty($post)){
                $model = new ProductModel();
                $adminid = Cookie::get('admin');
                $post['update_admin'] = $adminid;
                $post['update_time'] = time();
                $post['up_updatetime'] = time();
                $res = $model->allowField(true)->where(['id'=>$id])->update($post);
                if($res!==false){
                    return $this->success("修改成功");
                }else{
                    return $this->error("修改失败");
                }
            }else{
                return $this->error("修改失败");
            }
        }
        $trip['up_updatetime'] = !empty($trip['up_updatetime']) ? date("Y-m-d H:i",$trip['up_updatetime']) : '';
        $this->assign('trip',$trip);
        $this->assign('typeid',$typeid);
        return $this->fetch();
    }

    //下载附件
    public function uploadFile(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if($id==0){
            echo "文件路径错误";
            exit;
        }
        $product = db("product")->where('id',$id)->field('up_filename,up_url')->find();
        $fileName = $product['up_filename'];
        $url = $product['up_url'];
        $info = get_headers($url, true);
        $size = $info['Content-Length'];
        header("Content-type:application/octet-stream");
        header("Content-Disposition:attachment;filename = " . $fileName);
        header("Accept-ranges:bytes");
        header("Accept-length:" . $size);
        readfile($url);
        exit;
    }

    /**
     * 设置产品行程分段
     */
        public function setsectiontransport()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $trip = db("product")->find($id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        //获取行程原始数据
        list($trip_index_arr,$schedules) = $this->getProductScheduleData($id);
        $section_json = json_decode($trip['section_json'],true);
        $section_json = !empty($section_json)?$section_json:[];
        if(!empty($section_json)){
            $index = input("index","");
            if($index==""){
                return $this->error("请求错误！");
            }
            //分段节点数据
            $section_json = $this->getProductSectionJsonData($section_json,$schedules);
            $schedules = $this->getSectionTransport($section_json[$index],$schedules);
            $trip_index_arr = [];
            foreach ($schedules as $key=>$value){
                foreach ($value['children'] as $k=>$v){
                    $trip_index_arr[] = $key."-".$k;
                }
            }
            $section_json = [$section_json[$index]];
            $transport_json = json_decode($trip['section_trans_json'],true);
            $transport_json = !empty($transport_json)?$transport_json:[];
            //判断节点是否可选
            if(isset($transport_json[$index])){
                $transport_arr = $this->deconstructTransJson($transport_json[$index],$trip_index_arr);
                foreach ($schedules as $key=>$value){
                    foreach ($value['children'] as $child_key=>$child_value){
                        if(in_array($key.'-'.$child_key,$transport_arr)){
                            $schedules[$key]['disabled'] = true;
                            $schedules[$key]['children'][$child_key]['disabled'] = true;
                        }
                    }
                }
            }else{
                foreach ($schedules as $key=>$value){
                    foreach ($value['children'] as $child_key=>$child_value){
                        $schedules[$key]['disabled'] = false;
                        $schedules[$key]['children'][$child_key]['disabled'] = false;
                    }
                }
            }
        }else{
            return $this->error("请求错误！");
        }
        //展示交通列表
        if(isset($transport_json[$index])){
            $transList = $this->getDaysByTransJson($transport_json[$index],$schedules);
        }else{
            $transList = [];
        }
        $this->assign("transList",$transList);
        $this->assign('trip',$trip);
        $this->assign('index',$index);
        $this->assign('transport',$this->getTransportTitle());
        $this->assign("schedules",$schedules);
        $this->assign("sectionList",$section_json);
        return $this->fetch();
    }
    /**
     * 设置产品行程分段
     */
    public function setsection()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $standardtrip = db("standardtrip")->where(['sid'=>$id])->find();
        $trip_id = $standardtrip['trip_id'];
        $this->assign("standardtrip",$standardtrip);
        $trip = db("product")->find($trip_id);
        if(empty($trip)){
            return $this->error('行程信息有误');
        }
        //获取行程原始数据
        list($trip_index_arr,$schedules) = $this->getProductScheduleData($trip_id);
        $section_json = json_decode($trip['section_json'],true);
        $section_json = !empty($section_json)?$section_json:[];
        //所有节点均已设置
        $hasNotDisabled = false;
        if(!empty($section_json)){
            $section_arr = $this->deconstructSectionJson($section_json,$trip_index_arr);
            foreach ($schedules as $key=>$value){
                foreach ($value['children'] as $child_key=>$child_value){
                    if(in_array($key.'-'.$child_key,$section_arr)){
                        $schedules[$key]['disabled'] = true;
                        $schedules[$key]['children'][$child_key]['disabled'] = true;
                    }
                }
            }
            //判断是否所有节点均为已设置
            foreach ($schedules as $key=>$value){
                if($hasNotDisabled){
                    break;
                }
                foreach ($value['children'] as $child_key=>$child_value){
                    $disabled = $child_value['disabled']??false;
                    if(!$disabled){
                        //存在节点未设置
                        $hasNotDisabled = true;
                        break;
                    }
                }
            }
            //分段节点数据
            $section_json = $this->getProductSectionJsonData($section_json,$schedules);
            //包含具体交通类型的section
            $section_trans_json = json_decode($trip['section_trans_json'],true);
            $section_trans_json = !empty($section_trans_json)?$section_trans_json:[];
            $section_json = $this->getProSecTransJsonData($section_json,$section_trans_json);
        }else{
            $hasNotDisabled = true;
        }
        $this->assign('trip',$trip);
        $this->assign('transport',$this->getTransportTitle());
        $this->assign("schedules",$schedules);
        $this->assign("sectionList",$section_json);
        $this->assign("hasNotDisabled",$hasNotDisabled);
        $carTypeList = (new SDModel())->getCarTypeList();
        $this->assign("carTypeList",$carTypeList);
        //车型配置
        $carTypePriceList = [];
        if(!empty($trip['section_price_cartype'])){
            $carTypeIds = explode(',',$trip['section_price_cartype']);
            foreach ($carTypeIds as $value){
                $carTypePriceList[$value] = (new SDModel())->getCarTypeTitle($value);
            }
        }
        $this->assign("carTypePriceList",$carTypePriceList);
        return $this->fetch();
    }
    //获取分段配置的具体交通类型
    public function getProSecTransJsonData($section_json,$section_trans_json)
    {
        if(empty($section_json)) return [];
        if(empty($section_trans_json)) return $section_json;
        foreach ($section_json as $index=>$value){
            $transport_title = [];
            if(isset($section_trans_json[$index])){
                //排序
                $start_index = array_column($section_trans_json[$index],"start");
                array_multisort($start_index,SORT_ASC,$section_trans_json[$index]);
                foreach ($section_trans_json[$index] as $trans_k=>$trans_v){
                    $trans_type = $trans_v['type']??0;
                    $transport_title[] = $this->getTransportTitle($trans_type);
                }
            }
            $section_json[$index]['transport'] = implode(' >> ',$transport_title);
        }
        return $section_json;
    }
    //获取分段配置的交通类型
    public function getSectionTransport($section,$schedules)
    {
        $start = explode("-",$section['start']);
        $end = explode("-",$section['end']);
        if($start[0]==$end[0]){
            $children = array_slice($schedules[$start[0]]['children'],$start[1],$end[1]-$start[1]+1);
            $data = $schedules[$start[0]];
            $data['children'] = $children;
            $result[] = $data;
        }else{
            foreach ($schedules as $key=>$value){
                if($key<$start[0] || $key > $end[0]){
                    unset($schedules[$key]);
                }elseif($key==$start[0]){
                    foreach ($schedules[$key]['children'] as $kk=>$vv){
                        if($kk<$start[1]){
                            unset($schedules[$key]['children'][$kk]);
                        }
                    }
                    $schedules[$key]['children'] = array_values($schedules[$key]['children']);
                }elseif($key==$end[0]){
                    foreach ($schedules[$key]['children'] as $kk=>$vv){
                        if($kk>$end[1]){
                            unset($schedules[$key]['children'][$kk]);
                        }
                    }
                    $schedules[$key]['children'] = array_values($schedules[$key]['children']);
                }
            }
            $result = array_values($schedules);
        }
        return $result;
    }
    //分段交通设置 判断当前节点是否可选
    public function checkSeletedSection($transport,$schedules)
    {
        $start = explode("-",$transport['start']);
        $end = explode("-",$transport['end']);
        foreach ($schedules as $key=>$value) {
            if ($key < $start[0] || $key > $end[0]) {
                unset($schedules[$key]);
            } elseif ($key == $start[0]) {
                foreach ($schedules[$key]['children'] as $kk => $vv) {
                    if ($kk < $start[1]) {
                        unset($schedules[$key]['children'][$kk]);
                    }
                }
            } elseif ($key == $end[0]) {
                foreach ($schedules[$key]['children'] as $kk => $vv) {
                    if ($kk > $start[1]) {
                        unset($schedules[$key]['children'][$kk]);
                    }
                }
            }
        }
        return $schedules;
    }
    /**
     * 设置产品行程分段
     */
    public function setProductSection()
    {
        $post = request()->post();
        if(!empty($post)){
            $trip_id = isset($post['trip_id'])?$post['trip_id']:0;
            $days = isset($post['days'])?$post['days']:[];
            $items = isset($post['items'])?$post['items']:[];
            $trip = db("product")->find($trip_id);
            if(empty($trip)){
                $this->error("行程信息有误");exit;
            }
            if(empty($days) || empty($items)){
                $this->error("参数信息有误");exit;
            }
            $transItem = [];
            reset($items);
            $start = current($items);
            $end = end($items);
            $transItem[] = [
                'start'=>$start,
                'end'=>$end,
                'transport'=>0,
                'isBatch'=>1
            ];
            //对项目进行排序
            $_json = json_decode($trip['section_json'],true);
            $_json = !empty($_json)?$_json:[];
            $transJsonData = array_merge($_json,$transItem);
            $index = count($transJsonData)-1;
            $trans_json = json_encode($transJsonData);
            $res = db("product")->where(['id'=>$trip_id])->update(['section_json'=>$trans_json]);
            if($res!==false){
                //默认生成单段单日包车
                //$this->createOneProductSectionTransport($trip_id,$transJsonData[$index],$index);
                $this->success("保存成功","",$transJsonData);
            }else{
                $this->error("保存失败");
            }
        }else{
            $this->error("请求错误");exit;
        }
    }
    //删除分段
    public function delSection()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $index = $post['index']??"";
        $product = db("product")->find($id);
        if(empty($product) || empty($product['section_json'])){
            $this->error("删除失败");
        }
        $section_json = json_decode($product['section_json'],true);
        $section_trans_json = json_decode($product['section_trans_json'],true);
        if(!isset($section_json[$index])){
            $this->error("删除失败");
        }else{
            unset($section_json[$index]);
            if(isset($section_trans_json[$index])) unset($section_trans_json[$index]);
            $res = db("product")->where(['id'=>$id])->update(['section_json'=>json_encode($section_json),'section_trans_json'=>json_encode($section_trans_json)]);
            if($res){
                $this->success("删除成功");
            }else{
                $this->error("删除失败");
            }
        }
    }
    //清空分段设置
    public function delAllSection()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $index = $post['index']??"";
        $product = db("product")->find($id);
        if(empty($product)){
            $this->error("清空失败");
        }
        $res = db("product")->where(['id'=>$id])->update(['section_json'=>"",'section_trans_json'=>'']);
        if($res){
            $this->success("清空成功");
        }else{
            $this->error("清空失败");
        }
    }
    //组合交通分段数据 （包含交通数据） 用于核价
    public function pakeageSectionTransportData($tripId=0,$type="pricing")
    {
        $tripId = 1160;
        //$type = "pricing";//核价类型
        //$type = "unpack";//拆单类型
        //测试数据
        $trip = db("product")->find($tripId);
        //获取行程原始数据
        list($trip_index_arr,$schedules) = $this->getProductScheduleData($tripId);
        $trip = $trip??[];
        if(empty($trip)){
            return "error1";
        }
        $section_json = $trip['section_json']??"";
        if(empty($section_json)){
            return "error2";
        }
        $transport_json = $trip['section_trans_json']??"";
        if(empty($transport_json)){
            return "error3";
        }
        $section_json = json_decode($section_json,true);
        $transport_json = json_decode($transport_json,true);
        $section = [];
        //分段节点数据
        $section_json = $this->getProductSectionJsonData($section_json,$schedules);
        foreach ($section_json as $key=>$value){
            $schedules_arr = $this->getSectionTransport($section_json[$key],$schedules);
            //结合交通类型进行设置
            $transport_arr = $transport_json[$key]??[];
            $data = [];
            foreach ($transport_arr as $trans_k=>$trans_v){
                //依据类型进行设置不同的交通方式
                $model = new SDModel();
                if($type=="pricing"){
                    $data[] = $model->packageSectionDataPricing($trans_v,$schedules_arr);
                }elseif($type=="unpack"){
                    $data[] = $model->packageSectionDataUnpackOrder($schedules_arr);
                }
            }
            if(!empty($data)) $section[] = $data;
        }
        return json_encode(['section'=>$section]);
    }
    //分段配置页面保存每段的快速配置包车类型
    public function setTransportInSection()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $product = db("product")->find($id);
        if(empty($product)){
            $this->error("参数错误");
        }
        $trans_arr = $post['trans_arr']??[];
        if(empty($trans_arr)){
            $this->error("请选择包车类型");
        }else{
            $trans_arr = json_decode($post['trans_arr'],true);
        }
        $section_json = json_decode($product['section_json'],true);
        $section_trans_json = json_decode($product['section_trans_json'],true);
        if(empty($section_json)){
            $this->error("请先添加分段项");
        }
        //获取原始行程节点数据
        list($trip_index_arr,$schedules) = $this->getProductScheduleData($id);
        foreach ($trans_arr as $key=>$value){
            if(isset($section_json[$value['key']])){
                //赋值当前分段的包车类型
                $section_json[$value['key']]['transport'] = $value['transport'];
                $section_json[$value['key']]['isBatch'] = 1;
                $schedules_index = $this->getSectionTransport($section_json[$value['key']],$schedules);
                $lastSchedules = $schedules_index[count($schedules_index)-1];
                $start = "0-0";
                $end = (count($schedules_index)-1)."-".(count($lastSchedules['children'])-1);
                $section_trans_json[$value['key']] = [[
                    "type"=>$value['transport'],
                    'start'=>$start,
                    'end'=>$end
                ]];
            }
        }
        $section_json = json_encode($section_json);
        $section_trans_json = json_encode($section_trans_json);
        $res = db("product")->where(['id'=>$id])->update(['section_json'=>$section_json,'section_trans_json'=>$section_trans_json]);
        if($res){
            $this->success("保存成功");
        }else{
            $this->error("保存失败");
        }
    }
    //获取行程的原始节点数据
    public function getProductScheduleData($tripId)
    {
        $schedules = Db::name('pschedule')->field("id,displayorder,time,groupid")->where('groupid',$tripId)->order('displayorder')->select();
        $schedule_ids = array_column($schedules,"id");
        if(!empty($schedule_ids)) {
            $activeList = db('pactive a')
                ->join("city c", "c.id=a.cityid", 'left')
                ->join("poi p", "p.id=a.poiid", 'left')
                ->field("a.id,a.title,a.poiname,a.groupid,a.activeType,a.time as startingTime,a.content as remark,a.displayorder,a.title,a.poiid,a.cityid as cityId,c.name as cityName,c.kbx_id as kbxCityId,a.airport_lat,a.airport_lng,p.lat,p.lng,a.poiid")
                ->where(['a.groupid' => ['in', $schedule_ids]])
                ->order('a.groupid,a.displayorder')
                ->select();
        }
        $trip_index_arr = [];
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                $v = (new SDModel())->getAirportInfo($v);
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    $schedules[$key]['children'][] = $v;
                    //计算节点个数
                    $trip_index_arr[] = $key.'-'.(count($schedules[$key]['children'])-1);
                }
            }
        }
        return [$trip_index_arr,$schedules];
    }
    //获取行程的分段节点数据
    public function getProductSectionJsonData($section_json,$schedules)
    {
        foreach ($section_json as $key=>$value){
            $startday_index = explode("-",$value['start'])[0];
            $endday_index = explode("-",$value['end'])[0];
            $startpoi_index = explode("-",$value['start'])[1];
            $endpoi_index = explode("-",$value['end'])[1];
            $s_active_index =$schedules[$startday_index]['children'][$startpoi_index];
            $e_active_index =$schedules[$endday_index]['children'][$endpoi_index];
            $startpoi =  $s_active_index['poiname']??($s_active_index['title']??"");
            $endpoi = $e_active_index['poiname']??($e_active_index['title']??"");
            $pattern = '/[\x{4e00}-\x{9fa5}]/u';
            preg_match_all($pattern,$startpoi,$start_result);
            preg_match_all($pattern,$endpoi,$end_result);
            $startpoi =join('',$start_result[0]);
            $endpoi =join('',$end_result[0]);
            $section_json[$key]['startDayNum'] = $startday_index+1;
            $section_json[$key]['dayTitle'] = "第".($startday_index+1)."天:".$startpoi."  ---  第".($endday_index+1)."天:".$endpoi;
        }
        $dayNum = array_column($section_json,"startDayNum");
        array_multisort($section_json,SORT_ASC,$dayNum);
        return $section_json;
    }
    //默认将行程创建成一个段
    public function createOneProductSection($tripid)
    {
        $product = db("product")->find($tripid);
        if(empty($product)){
            return false;
        }
        //获取原始行程节点数据
        list($trip_index_arr,$schedules) = $this->getProductScheduleData($tripid);
        $start = "0-0";
        $lastSchedule = $schedules[count($schedules)-1];
        $end = (count($schedules)-1)."-".(count($lastSchedule['children'])-1);
        $section_json[0] = [
            'start'=>$start,
            'end'=>$end,
            'transport'=>0,
            'isBatch'=>1
        ];
        db("product")->where(['id'=>$tripid])->update(['section_json'=>json_encode($section_json)]);
        //将单个段设置默认一日包车
        //$this->createOneProductSectionTransport($tripid,$section_json[0],0);
    }
    //默认将一个段设置成一日包车
    public function createOneProductSectionTransport($tripid,$section_json,$index)
    {
        $trip = db("product")->find($tripid);
        if(empty($trip)){
            return false;
        }
        //获取原始行程节点数据
        list($trip_index_arr,$schedules) = $this->getProductScheduleData($tripid);
        $schedules = $this->getSectionTransport($section_json,$schedules);
        $lastChildren = end($schedules);
        $end = (count($schedules)-1).'-'.(count($lastChildren['children'])-1);
        //默认设置市区一日包车
        $transportItem[] = [
            'type'=>4,//市区一日
            'start'=>'0-0',
            'end'=>$end
        ];
        //对项目进行排序
        $_json = json_decode($trip['section_trans_json'],true);
        $_json[$index] = $_json[$index]??[];
        $_json[$index] = array_merge($_json[$index],$transportItem);
        $trans_json = json_encode($_json);
        db("product")->where(['id'=>$tripid])->update(['section_trans_json'=>$trans_json]);
    }
    //初步设置价格 【根据车型生成对应的数据，并未手动配置价格】
    public function setSectionPriceData()
    {
        $post = request()->post();
        $tripid = $post['trip_id']??0;
        $carTypeIds = $post['carTypeIds']??"";
        $product = db("product")->where(['id'=>$tripid])->find();
        if(empty($product)){
            $this->error("请求错误1");
        }
        $carTypeIds = explode(",",$carTypeIds);
        if(empty($carTypeIds)){
            $this->error("请求错误2");
        }else{
            sort($carTypeIds);
        }
        //保存当前车辆配置
        db("product")->where(['id'=>$tripid])->update(['section_price_cartype'=>implode(",",$carTypeIds)]);
        //删除原来的配置
        db("psection")->where(['product_id'=>$tripid,'car_type'=>['not in',$carTypeIds]])->delete();
        //获取当前分段的内容
        $insertData = [];
        //获取原来的设置
        foreach ($carTypeIds as $cartype){
            $res = db("psection")->where(['product_id'=>$tripid,'car_type'=>$cartype])->find();
            //新增价格配置
            if(empty($res)){
                $insertData[] = [
                    'product_id'=>$tripid,
                    'car_type'=>$cartype,
                    'updatetime'=>time(),
                    'createtime'=>time()
                ];
            }
        }
        if(!empty($insertData)){
            $res = db('psection')->insertAll($insertData);
            if(empty($res)){
                $this->error("获取失败");
            }
        }
        $price = db("psection")->where(['product_id'=>$tripid])->order("car_type asc")->select();
        foreach ($price as $key=>$value){
            $price[$key]['carTypeTitle'] = (new SDModel())->getCarTypeTitle($value['car_type']);
            $price[$key]['price'] = empty($value['section_json'])?[]:json_decode($value['section_json'],true);
        }
        $this->success("获取成功",'',$price);
    }
    /**
     *通过车辆类型进行核价操作
     */
    public function getProductSectionPriceByCarType()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $carType = $post['carType']??"";
        $product = db("product")->where(['id'=>$tripid])->find();
        if(empty($product)){
            $this->result([],0,'产品信息有误','json');
        }
        if(empty($carType)){
            $this->result([],0,'核价失败','json');
        }
        //进行核价
        $carTypeList = explode(',',$carType);
        $priceData = [];
        foreach ($carTypeList as $car_k=>$car_v){
            $priceData[$car_k]['type'] = $car_v;
            $priceData[$car_k]['section_json'] = $this->checkSectionCarPrice($tripid,$car_v);
        }
        //核价完成
        if(!empty($priceData)){
            $this->result($priceData,1,'核价成功','json');
        }else{
            $this->result([],0,'核价失败','json');
        }
    }

    //根据特定车型获取核价数据【测试】
    public function testProductSectionPriceByCarType()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $carType = $post['carType']??"";
        $product = db("product")->where(['id'=>$tripid])->find();
        if(empty($product)){
            $this->error("请求错误");
        }
        if(empty($carType)){
            $this->error("请求错误");
        }
        //进行核价
        $carTypeList = explode(',',$carType);
        $priceData = [];
        foreach ($carTypeList as $car_k=>$car_v){
            $priceData[$car_k]['type'] = $car_v;
            $priceData[$car_k]['section_json'] = $this->testCheckSectionCarPrice($tripid,$car_v);
        }
        return json_encode($priceData);exit;
    }
    //保存自定义报价
    public function saveProductSectionPriceData()
    {
        $post = request()->post();
        $tripid = $post['id']??0;
        $carPriceData = $post['carPriceData']??[];
        $currency = $post['currency']??"";
        if(empty($carPriceData)){
            $this->error("请填写价格");
        }
        if(empty($currency)){
            $this->error("请选择派单价单位");
        }
        db::startTrans();
        try{
            foreach($carPriceData as $key=>$value){
                $psection = db("psection")->where(['product_id'=>$tripid,'car_type'=>$value['car_type']])->find();
                if(!empty($psection)){
                    db("psection")
                        ->where(['product_id'=>$tripid,'car_type'=>$value['car_type']])
                        ->update([
                        'section_json'=>json_encode($value['price']),
                        'updatetime'=>time()
                    ]);
                }
            }
            //设置派单价单位
            db("standardtrip")->where(['trip_id'=>$tripid])->update(['costCurrency'=>$currency]);
            $standardtrip = db("standardtrip")->where(['trip_id'=>$tripid])->find();
            db("standard")->where(['id'=>$standardtrip['sid']])->update(['page_index'=>$post['page_index']]);
            db::commit();
            $this->success("行程成本配置成功");
        }catch(Exception $e){
            db::rollback();
            $this->success("行程成本配置失败");
        }
    }
    //组装包车核价数据
    public function checkSectionCarPrice($product_id,$carType)
    {
        $product = db("product")->find($product_id);
        $section_json = json_decode($product['section_json'],true);
        $section_trans_json = json_decode($product['section_trans_json'],true);
        list($trip_index_arr,$schedules)  = $this->getProductScheduleData($product_id);
        foreach ($section_json as $key=>$value){
            $schedules_arr = $this->getSectionTransport($value,$schedules);
            //核价的原始数据
            if(isset($section_trans_json[$key])){
                $section_carprice = $this->packageSectionCarPirce($schedules_arr,$section_trans_json[$key],$carType);
                //调用接口进行核价
                list($totalAmount,$amountDetails,$currency) = $this->getOrderSystemTransportDataByProduct($section_carprice);
            }else{
                list($totalAmount,$amountDetails,$currency) = [0,[],"USD"];
            }
            //将核价数据进行封装
            $section_json[$key]['totalAmount'] = $totalAmount;
            $section_json[$key]['currency'] = $currency;
            $section_json[$key]['amountDetails'] = $amountDetails;
        }
        return $section_json;
    }
    //组装包车核价数据
    public function testCheckSectionCarPrice($product_id,$carType)
    {
        $product = db("product")->find($product_id);
        $section_json = json_decode($product['section_json'],true);
        $section_trans_json = json_decode($product['section_trans_json'],true);
        $section_carprice = [];
        list($trip_index_arr,$schedules)  = $this->getProductScheduleData($product_id);
        foreach ($section_json as $key=>$value){
            $schedules_arr = $this->getSectionTransport($value,$schedules);
            //核价的原始数据
            if(isset($section_trans_json[$key])){
                $section_carprice[] = $this->packageSectionCarPirce($schedules_arr,$section_trans_json[$key],$carType);
            }
        }
        return $section_carprice;
    }
    /**
     * 组装包车核价数据
     * @param $schedules 当前行程的日程
     * @param $section_trans 当前日程的每天的类型
     */
    public function packageSectionCarPirce($schedules,$section_trans,$carType)
    {
        $postData = [];
        //检测是否更换天数 以天为单位保存activities
        $schedules_ids = [];
        foreach ($section_trans as $key=>$value){
            $trans_type = $value['type'];
            $trans_type = $this->getTransportType($trans_type);
            $startday_index = explode("-",$value['start'])[0];
            $endday_index = explode("-",$value['end'])[0];
            $startpoi_index = explode("-",$value['start'])[1];
            $endpoi_index = explode("-",$value['end'])[1];
            $activities = [];
            //同一天
            if($startday_index==$endday_index){
                $activeList = array_slice($schedules[$startday_index]['children'],$startpoi_index,$endpoi_index-$startpoi_index+1);
                $activity = $this->getSectionTransportActivities(
                    $trans_type,
                    $carType,
                    $activeList);
                if(!empty($activity)){
                    $activities[] = $activity;
                }
                //检查日期是否重复
                $schedules_id = $schedules[$startday_index]['id'];
                if(!in_array($schedules_id,$schedules_ids)){
                    $postData[] = [
                        'id'=>$schedules_id,
                        'label'=>$schedules[$startday_index]['label'],
                        'activities'=>$activities
                    ];
                    $schedules_ids[] = $schedules_id;
                }else{
                    $id_index = array_search($schedules_id,$schedules_ids);
                    $postData[$id_index]['activities'] = array_merge($postData[$id_index]['activities'],$activities);
                }
            }elseif($startday_index<$endday_index){
                for ($i=$startday_index;$i<=$endday_index;$i++){
                    //每天开始重置所有包车类型
                    $activities = [];
                    if($i == $startday_index){
                        $max = count($schedules[$startday_index]['children']);
                        $activeList = array_slice($schedules[$i]['children'],$startpoi_index,$max-$startday_index+1);
                    }elseif($i<$endday_index){
                        $activeList = $schedules[$i]['children'];
                    }elseif($i == $endday_index){
                        $activeList = array_slice($schedules[$i]['children'],0,$endpoi_index+1);
                    }
                    $activity = $this->getSectionTransportActivities(
                        $trans_type,
                        $carType,
                        $activeList);
                    if(!empty($activity)){
                        $activities[] = $activity;
                    }else{
                        continue;
                    }
                    //检查日期是否重复
                    $schedules_id = $schedules[$i]['id'];
                    if(!in_array($schedules_id,$schedules_ids)){
                        $postData[] = [
                            'id'=>$schedules_id,
                            //'label'=>$schedules[$i]['label'],
                            'activities'=>$activities
                        ];
                        $schedules_ids[] = $schedules_id;
                    }else{
                        $id_index = array_search($schedules_id,$schedules_ids);
                        $postData[$id_index]['activities'] = array_merge($postData[$id_index]['activities'],$activities);
                    }
                }
            }
        }

        //补充没有设置包车的数据【定制包车包含日期】 产品核价没有日期直接跳过
        $list = [];
        $prev_time = 0;
        $maxDay = 10;//最多间隔时间 10天
        if(!empty($postData)){
            foreach ($postData as $key=>$value){
                if(!empty($value['activities'][0]['time'])){
                    //去除首位两端的数据
                    if(!empty($prev_time) &&
                        $prev_time!=strtotime($value['activities'][0]['time'])
                    ){
                        $i=0;
                        while($prev_time!=strtotime($value['activities'][0]['time']) && $i<$maxDay){
                            $list[] = [
                                'id'=>0,
                                'label'=>'未设置包车',
                                'activities'=>[
                                    ['time'=>date('Y-m-d',$prev_time)]
                                ],
                            ];
                            $prev_time += 24*3600;
                            $i++;//防止死循环
                        }
                    }
                    $list[] = $value;
                    $prev_time = strtotime($value['activities'][0]['time'])+24*3600;
                }
            }
        }
        return empty($list)?$postData:$list;
    }
    public function getSectionTransportActivities($trans_type,$carType,$children)
    {
        $from = $to = $pois = [];
        $firstCityId = "";
        foreach ($children as $kk=>$value){
            if(!empty($value['lat']) && !empty($value['lng'])){
                //机场节点需要 获取新的经纬度
                if(in_array($value['activeType'],[2,3])){
                    $value['lat'] = $value['airport_lat'];
                    $value['lng'] = $value['airport_lng'];
                }
                if(empty($from)){
                    $from = [
                        'city'=>$value['kbxCityId'],
                        'location'=>[
                            'lat'=>$value['lat'],
                            'lng'=>$value['lng'],
                        ]
                    ];
                    $firstCityId = $value['kbxCityId'];
                    if(in_array($trans_type,[
                            "Transport_Vehicle_FromAirport",
                            "Transport_Vehicle_ToAirport"
                        ])){
                        $from['placeId'] = $value['poiid'];
                    }
                }
                $to =[
                    'city'=>$value['kbxCityId'],
                    'location'=>[
                        'lat'=>$value['lat'],
                        'lng'=>$value['lng'],
                    ]
                ];
                if(in_array($trans_type,[
                    "Transport_Vehicle_FromAirport",
                    "Transport_Vehicle_ToAirport"
                ])){
                    $to['placeId'] = $value['poiid'];
                }
                $pois[] = [
                    'location'=>[
                        //'label'=>$value['label'],//显示poi名称
                        'lat'=>$value['lat'],
                        'lng'=>$value['lng'],
                    ]
                ];
            }
        }
        //判断是否存在可以使用的节点
        if(!empty($from)){
            array_shift($pois);
            array_pop($pois);
            $activities = [
                'time'=>$children[0]['time']??"",
                'type'=>$trans_type,
                'carType'=>$carType,
                'city'=>$firstCityId,
                'from'=>$from,
                'to'=>$to,
                'pois'=>$pois
            ];
        }else{
            $activities = [];
        }
        return $activities;
    }
    //测试订单系统的标品产品的包车核价
    public function getOrderSystemTransportDataByProduct($post_data,$tripType="pro",$tripid=0)
    {
        //调用接口查询价格
        $KbxOther = new KbxOther();
        $priceData = $KbxOther->getCarPrice(['fullTravel'=>$post_data]);
//        var_dump(json_encode(['fullTravel'=>$post_data]));exit;
//        var_dump($priceData);exit;
        $result = json_decode($priceData,true);
        if(isset($result['msg'])){
            return [-1,$result['msg'],''];
        }
        $data = [];
        //获取总价格
        $totalAmount = 0;
        $currency = "";
        $amountDetails = [];
        $activitiesSnap = [];
        if(!empty($result)){
            foreach ($result as $key=>$value){
                $activities = $value['activities'];
                foreach ($activities as $act_k=>$act_v){
                    if(!isset($act_v['time'])){
                        //司导返程类型没有time时间 需要从上一个节点获取
                        $activities[$act_k]['time'] = $activities[$act_k-1]['time']??"";
                        $activities[$act_k]['currency'] = $activities[$act_k-1]['currency']??"USD";
                        $activities[$act_k]['displayString'] = '-'.$act_v['displayString'];
                        $activities[$act_k]['serviceType'] = "";
                    }
                }
                $activitiesSnap = array_merge($activitiesSnap,$activities);
                if(empty($currency) && isset($activities[0]['currency'])){
                    $currency = $activities[0]['currency']??"";
                }
                $amountDetails[] = $this->getOrderSystemPricingDetails($activities);
                $totalAmount += $value['totalAmount']??0;
            }
            $currency = $currency?:"CNY";//默认人民币
            //如果是定制行程 需要缓存价格
            if($tripType=="trip" && !empty($tripid)){
                $trip = db('trip')->where(['id'=>$tripid])->find();
                if(!empty($trip)){
                    $tripActivitiesSnap = empty($trip['activitiesSnap'])?[]:json_decode($trip['activitiesSnap']);
                    $tripActivitiesSnap = array_merge($tripActivitiesSnap,$activitiesSnap);
                    db('trip')->where(['id'=>$tripid])->update(['activitiesSnap'=>json_encode($tripActivitiesSnap)]);
                }
            }
        }
        return [$totalAmount,$amountDetails,$currency];
    }
    //获取核价的详细信息
    public function getOrderSystemPricingDetails($activities)
    {
        $detailsData = [];
        if(empty($activities)){
            return [];
        }
        foreach ($activities as $key=>$value){
            $details = [];
            $details['displayString'] = $value['displayString']??"";
            $details['currency'] = $value['currency']??"";
            if(isset($value['distance']) && !empty($value['distance'])){
                $details['distance'] = $value['distance']>1000?(intval($value['distance']/10)/100).'km':(intval($value['distance']*100)/100).'m';
            }
            if(isset($value['distance']) && !empty($value['duration'])){
                $details['duration'] = $value['duration']>3600?(intval($value['duration']*100/3600)/100).'小时':(intval($value['duration']*100/60)/100).'分钟';
            }
            if(isset($value['baseAmount']) && !empty($value['baseAmount'])) $details['baseAmount'] = $value['baseAmount'];//基础费用
            if(isset($value['extra']['oilFee']) && !empty($value['extra']['oilFee'])) $details['oilFee'] = $value['extra']['oilFee'];//油费
            if(isset($value['extra']['exceedKMFee']) && !empty($value['extra']['exceedKMFee'])) $details['exceedKMFee'] = $value['extra']['exceedKMFee'];//超出基础里程费用
            if(isset($value['extra']['overtimeFee']) && !empty($value['extra']['overtimeFee'])) $details['overtimeFee'] = $value['extra']['overtimeFee'];//超时费
            if(isset($value['extra']['hotelFee']) && !empty($value['extra']['hotelFee'])) $details['hotelFee'] = $value['extra']['hotelFee'];//司导酒店费用
            if(isset($value['extra']['dinnerFee']) && !empty($value['extra']['dinnerFee'])) $details['dinnerFee'] = $value['extra']['dinnerFee'];//餐补
            if(isset($value['extra']['nightFee']) && !empty($value['extra']['nightFee'])) $details['nightFee'] = $value['extra']['nightFee'];
            if(isset($value['extra']['parkingFee']) && !empty($value['extra']['parkingFee'])) $details['parkingFee'] = $value['extra']['parkingFee'];//停车费
            if(isset($value['extra']['assistanceFee']) && !empty($value['extra']['assistanceFee'])) $details['assistanceFee'] = $value['extra']['assistanceFee'];//陪护费用，导游费用
            if(isset($value['extra']['childSeatFee']) && !empty($value['extra']['childSeatFee'])) $details['childSeatFee'] = $value['extra']['childSeatFee'];//儿童座椅
            if(isset($value['totalAmount']) && !empty($value['totalAmount'])) $details['totalAmount'] = $value['totalAmount'];//总费用
            $detailsData[] = $details;
        }
        return $detailsData;
    }

    //修改门票的状态
    public function setTicketStatus(){
        $post = $this->request->post();
        $active_id = $post['active_id'];
        $value = $post['value'];
        if($value==0){
            $ticket_status = 1;
        }else{
            $ticket_status = 0;
        }
        $res = db("pactive")->where("id",$active_id)->update(['ticket_status'=>$ticket_status]);
        if($res!==false){
            return $this->success("修改成功");
        }else{
            return $this->error("修改失败");
        }
    }



    //**********************价格配置***********************************************
    //*****************************************************************************
    //产品套餐规格配置
    public function addPackage(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $table_name = ['规格名称','库存','最低下单数','最小增长数'];
        //是新增操作
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post()['data'];
            Db::startTrans(); //启动事务
            try {
                //********************套餐********************
                //将全部套餐status都设置为2
                Db::name('product_package')->where("product_id",$id)->update(['status'=>2]);

                $packageData['product_id'] = $id;
                foreach ($post as $key=>$value){
                    $packageData['name'] = $value['package_name'];
                    $packageData['status'] = 1;
                    if(!empty($value['package_id'])){
                        $packageData['updatetime'] = time();
                        Db::name('product_package')->where("id",$value['package_id'])->update($packageData);

                        //********************规格********************
                        $specsData['package_id'] = $value['package_id'];
                        $specsData['updatetime'] = time();
                        $specsData['status'] = 1;
                        if(!empty($value['specsdata'])){
                            //将全部规格status都设置为2
                            Db::name('product_specs')->where("package_id",$value['package_id'])->update(['status'=>2]);
                            foreach ($value['specsdata'] as $k=>$v){
                                $specsData['name'] = $v['specs_name'];
                                $specsData['num'] = $v['specs_num'];
                                $specsData['minorder_num'] = $v['minorder_num'];
                                $specsData['inc_order_num'] = $v['inc_order_num'];
                                if(!empty($v['specs_id'])){
                                    Db::name('product_specs')->where("id",$v['specs_id'])->update($specsData);
                                }else{
                                    $specsData['creattime'] = time();
                                    Db::name('product_specs')->insert($specsData);
                                }
                            }
                        }
                    }else{
                        $packageData['creattime'] = time();
                        $packageData['updatetime'] = time();
                        Db::name('product_package')->insert($packageData);

                        $package_id = Db::name('product_package')->getLastInsID();//规格id
                        $specsData['package_id'] = $package_id;
                        $specsData['creattime'] = time();
                        $specsData['updatetime'] = time();
                        $specsData['status'] = 1;
                        if(!empty($value['specsdata'])){
                            foreach ($value['specsdata'] as $k=>$v){
                                $specsData['name'] = $v['specs_name'];
                                $specsData['num'] = $v['specs_num'];
                                $specsData['minorder_num'] = $v['minorder_num'];
                                $specsData['inc_order_num'] = $v['inc_order_num'];
                                Db::name('product_specs')->insert($specsData);
                            }
                        }
                    }
                }
                Db::commit(); //提交事务

                //删除套餐数据
                $this->delSpecsAndPerson($id);

                return $this->success('提交产品套餐规格成功');
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error('提交产品套餐规格失败');
            }
        }else{
            $package = Db::name('product_package')->where("product_id",$id)->where("status",1)->select();
            if($package){
                foreach($package as $key=>$value){
                    $package[$key]['specs'] = [];
                    $package_id = $value['id'];

                    $specs = Db::name('product_specs')->where("package_id",$package_id)->where("status",1)->select();

                    array_push($package[$key]['specs'],$specs);
                }
                $this->assign('package',$package);
            }else{
                $this->assign('package','');
            }
        }

        $this->assign('id',$id);
        $this->assign('table_name',$table_name);
        return $this->fetch();
    }

    //删除套餐数据
    protected function delSpecsAndPerson($id)
    {
        $product = db("product")->where("id",$id)->field("id")->find();
        if(!empty($product)){
            $packageIdArr = db("product_package")->where(["product_id"=>$id,"status"=>2])->column("id");
            if(!empty($packageIdArr)){
                DB::startTrans();//开启事务
                try{
                    //直接删除套餐后，规格价格也一并删除
                    db("product_package")->where(["product_id"=>$id,"status"=>2,"id"=>["in",$packageIdArr]])->delete();
                    $specsIdArr = db("product_specs")->where(["package_id"=>["in",$packageIdArr]])->column("id");
                    db("product_specs")->where(["package_id"=>["in",$packageIdArr]])->delete();
                    db("product_dailyprice")->where(["specs_id"=>["in",$specsIdArr]])->delete();
                    //更新价格区间
                    $this->updateProductPriceSection($id);
                    //提交事务
                    DB::commit();
                    return true;
                }catch(\PDOException $e){
                    //回滚事务
                    DB::rollback();
                    return false;
                }
            }
        }
    }
    //ajax删除套餐
    public function delPackage()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $package = db("product_package")->where("id",$post['id'])->find();
            if(empty($package)){
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
            db::startTrans();
            try{
                db("product_package")->delete($post['id']);
                $specsIdArr = db("product_specs")->where("package_id",$post['id'])->column("id");
                db("product_specs")->where("package_id",$post['id'])->delete();
                db("product_dailyprice")->where(["specs_id"=>["in",$specsIdArr]])->delete();
                //更新价格区间
                $this->updateProductPriceSection($package['product_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }
    //ajax删除规格
    public function delSpecs()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $specs = db("product_specs")->where("id",$post['id'])->find();
            if(empty($specs)){
                return json(['code'=>-2,"msg"=>'删除失败']);
            }
            $package = db("product_package")->where("id",$specs['package_id'])->find();
            if(empty($package)){
                return json(['code'=>-3,"msg"=>'删除失败']);
            }
            db::startTrans();
            try{
                db("product_specs")->where("id",$post['id'])->delete();
                db("product_dailyprice")->where("specs_id",$specs['id'])->delete();
                //更新价格区间
                $this->updateProductPriceSection($package['product_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }

    //*****************************************************************************
    //展示价格日历
    //价格设置   setprice未使用
    public function setprice(){
        $product_id = input('id');
        $product = db("product")->find($product_id);
        //判断是否存在默认套餐
        $this->setDefaultSpec($product_id);

        //派单价格
        $carPriceArr = ['f_cost'=>0,'s_cost'=>0,'t_cost'=>0];
        $standard = db("standard")
            ->alias("s")
            ->join("standardtrip st","s.id=st.sid","left")
            ->where("st.trip_id",$product_id)
            ->field("s.*")
            ->find();
        if(!empty($standard)){
            //查询已配置过的派单价格
            $psection = db("psection")
                ->alias("p")
                ->join("standardtrip s","p.product_id=s.trip_id","left")
                ->where("s.sid",$standard['id'])
                ->field("p.*")
                ->select();

            if(!empty($psection)){
                foreach ($psection as $key=>$value) {
                    $section_json = json_decode($value['section_json'],true);
                    $price = 0;
                    if(!empty($section_json)){
                        foreach ($section_json as $k=>$v) {
                            $price += intval($v);
                        }
                    }
                    if($value['car_type']==1){
                        $carPriceArr['f_cost'] = $price;
                    }elseif($value['car_type']==10){
                        $carPriceArr['s_cost'] = $price;
                    }elseif($value['car_type']==20){
                        $carPriceArr['t_cost'] = $price;
                    }
                }
            }
        }

        $currencySet = [];
        $currencyList = (new Common())->getCurrencyListByCity();
        foreach ( $currencyList as $currency_v){
            $currencySet[$currency_v['currency_code']] = [
                'currSymbol'=>$currency_v['currency_symbol'],
                'currName'=>$currency_v['currency_name'],
            ];
        }
        $exchangeData = db("exchange")->select();
        $exchange = [];
        foreach ($exchangeData as $k=>$v) {
            $exchange[$v['currency_code']] = $v['exchange_rate'];
        }

        $currencyCode = $product['currency'];
        $currency = $currencySet[$currencyCode]['currSymbol'];
        $currencyName = $currencySet[$currencyCode]['currName'];
        $exchangeNum = $exchange[$currencyCode]??'';

        $starttime = date("Y-m-d",$product['sale_starttime']);
        $endtime = date("Y-m-d",$product['sale_endtime']);
        $dailyPrice = db("product_dailyprice")->where(["product_id"=>$product_id,'time'=>['between',[$starttime,$endtime]]])->order("id asc")->select();
        //按天封装数据
        $data = [];
        foreach ($dailyPrice as $value){
            $data[$value['time'].",".$value['package_id']][] = $value;
        }
        $this->assign('product',$product)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime)
            ->assign('currency',$currency)
            ->assign('currencyName',$currencyName)
            ->assign('exchangeNum',$exchangeNum)
            ->assign('carPriceArr',$carPriceArr);

        return $this->fetch();
    }

    //getPriceForMake被productmake调用
    public function getPriceForMake($product_id){
        $product = db("product")->find($product_id);
        //判断是否存在默认套餐
        $this->setDefaultSpec($product_id);

        //派单价格
        $carPriceArr = ['f_cost'=>0,'s_cost'=>0,'t_cost'=>0];
        $standard = db("standard")
            ->alias("s")
            ->join("standardtrip st","s.id=st.sid","left")
            ->where("st.trip_id",$product_id)
            ->field("s.*")
            ->find();
        if(!empty($standard)){
            //查询已配置过的派单价格
            $psection = db("psection")
                ->alias("p")
                ->join("standardtrip s","p.product_id=s.trip_id","left")
                ->where("s.sid",$standard['id'])
                ->field("p.*")
                ->select();

            if(!empty($psection)){
                foreach ($psection as $key=>$value) {
                    $section_json = json_decode($value['section_json'],true);
                    $price = 0;
                    if(!empty($section_json)){
                        foreach ($section_json as $k=>$v) {
                            $price += intval($v);
                        }
                    }
                    if($value['car_type']==1){
                        $carPriceArr['f_cost'] = $price;
                    }elseif($value['car_type']==10){
                        $carPriceArr['s_cost'] = $price;
                    }elseif($value['car_type']==20){
                        $carPriceArr['t_cost'] = $price;
                    }
                }
            }
        }

        $currencySet = [];
        $currencyList = (new Common())->getCurrencyListByCity();
        foreach ( $currencyList as $currency_v){
            $currencySet[$currency_v['currency_code']] = [
                'currSymbol'=>$currency_v['currency_symbol'],
                'currName'=>$currency_v['currency_name'],
            ];
        }
        $exchangeData = db("exchange")->select();
        $exchange = [];
        foreach ($exchangeData as $k=>$v) {
            $exchange[$v['currency_code']] = $v['exchange_rate'];
        }

        $currencyCode = !empty($product['currency']) ? $product['currency'] : 'USD';
        $currency = $currencySet[$currencyCode]['currSymbol'];
        $currencyName = $currencySet[$currencyCode]['currName'];
        $exchangeNum = $exchange[$currencyCode]??'';

        $starttime = date("Y-m-d",$product['sale_starttime']);
        $endtime = date("Y-m-d",$product['sale_endtime']);
        $dailyPrice = db("product_dailyprice")->where(["product_id"=>$product_id,'time'=>['between',[$starttime,$endtime]]])->order("id asc")->select();
        //按天封装数据
        $data = [];
        foreach ($dailyPrice as $value){
            $data[$value['time'].",".$value['package_id']][] = $value;
        }
        $this->assign('product',$product)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime)
            ->assign('currency',$currency)
            ->assign('currencyName',$currencyName)
            ->assign('exchangeNum',$exchangeNum)
            ->assign('carPriceArr',$carPriceArr);

        return true;
    }

    //不存在套餐时 默认生成套餐A
    public function setDefaultSpec($product_id){
        //检测是否存在产品
        $product = db("product")->find($product_id);
        if(empty($product_id) || empty($product)) return false;
        //检测是否已经存在套餐 如存在直接跳过
        $package = db("product_package")->where(['product_id'=>$product_id])->find();
        if(!empty($package)) return false;
        //生成新套餐
        $res = db('product_package')->insert([
            "product_id"=>$product_id,
            "name"=>"套餐A",
            "status"=>1,
            "creattime"=>time(),
            "updatetime"=>time(),
        ]);
        return $res;
    }

    //ajax查詢套餐
    public function werk(){
        $product_id = input('id');
        $list =	db('product_package')->where('product_id',$product_id)->where('status',1)->select();
        if(empty($list)){
            return json(['code'=>-1,'data'=>$list]);
        }else{
            return json(['code'=>200,'data'=>$list]);
        }
    }

    //ajax查詢规格
    public function pos(){
        $package_id = input('package_id');
        $list =	db('product_specs')->where('package_id',$package_id)->where('status',1)->select();
        return json($list);
    }

    //获取产品全部日期价格集合
    public function getPrice(){
        $product_id = input('id');
        $sdate = input('sdate');
        $edate = input('edate');
        $personday = db("product_dailyprice")->where(["product_id"=>$product_id,'time'=>['between',[$sdate,$edate]]])->select();
        //按天封装数据
        $data = [];
        foreach ($personday as $value){
            $data[$value['time'].",".$value['package_id']][] = $value;
        }
        return json(['code'=>200,'msg'=>'ko','data'=>$data]);
    }

    //*********普通成本设置*****************************************************
    //【普通成本】价格配置提交
    public function ajaxsetgoodsprice(){
        $post = request()->post();
        $param = json_decode($post['param'],true);
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $this->addPersonList($param['package_id'],$param['specs'],$param['date']);

            db::commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败'.$e]);
        }
    }
    //写入库表
    protected function addPersonList($package_id,$specs,$date){
        if(empty($specs))return false;
        if(empty($date))return false;
        $package_info = db("product_package")->find($package_id);
        if(empty($package_info))return false;
        $del_res = db("product_dailyprice")
            ->where(['package_id'=>$package_id,'time'=>['in',$date]])
            ->delete();
        //删除已有套餐日期价格数据
        if($del_res===false)return false;

        $vehicle_type = 0;
        if($package_info['vehicle_type']!==$vehicle_type) {
            $del_res = db("product_dailyprice")->where(['package_id' => $package_id])->delete();
            //删除失败
            if ($del_res === false) return false;

            db("product_package")
                ->where("id",$package_id)
                ->update([
                    'vehicle_type'=>$vehicle_type,
                    'updatetime'=>time()
                ]);
        }

        foreach ($specs as $key => $value) {
            $insertAll = [];
            $product_specs = db("product_specs")->find($value['id']);
            foreach ($date as $day) {
                $insertAll[] = [
                    'time' => $day,
                    'product_id' => $package_info['product_id'],
                    'package_id' => $package_id,
                    'specs_id' => $value['id'],
                    'name' => $product_specs['name'],
                    'price' => $value['price'],
                    'num' => $product_specs['num'],
                    'minorder_num' => $product_specs['minorder_num'],
                    'inc_order_num' => $product_specs['inc_order_num'],
                ];
            }
            //插入数据
            db("product_dailyprice")->insertAll($insertAll);
            //更新价格区间
            $this->updateProductPriceSection($package_info['product_id']);
        }
    }

    //【批量删除】
    public function delsetgoodsprice()
    {
        $post = request()->post();
        $param = json_decode($post['param'],true);
        //判断日期是否重叠
        $package_id = $param['package_id'];
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $this->deletePersonList($package_id,$param['date']);
            db::commit();
            return json(['code'=>200,'msg'=>'删除成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'删除失败']);
        }
    }
    //删除表记录
    protected function deletePersonList($package_id,$date){
        if(empty($date))return false;
        $package_info = db("product_package")->find($package_id);
        if(empty($package_info))return false;
        $res = db("product_dailyprice")
            ->where(['package_id'=>$package_id,'time'=>['in',$date]])
            ->delete();
        //更新价格区间
        $this->updateProductPriceSection($package_info['product_id']);
        return $res;
    }

    //单独设置某天的价格
    public function setSingleDayPrice()
    {
        $post = request()->post();
        $postdata = $post['data']??"";
        $product_id = $post['product_id']??0;
        if(empty($postdata) || empty($product_id)){
            return json(['code'=>-1,'msg'=>'保存失败']);
        }
        $priceArr = json_decode($postdata,true);
        if(empty($priceArr)){
            return json(['code'=>-1,'msg'=>'保存失败']);
        }
        db::startTrans();
        try{
            foreach ($priceArr as $value){
                $dailyprice = db("product_dailyprice")->find($value['id']);
                if(!empty($dailyprice) && $dailyprice['price']!=$value['price']){
                    db("product_dailyprice")->where('id',$value['id'])->update(['price'=>$value['price']]);
                }
            }
            //更新价格区间
            $this->updateProductPriceSection($product_id);
            db::commit();
            return json(['code'=>200,'msg'=>'保存成功']);
        }catch (Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'保存失败']);
        }
    }


    //*********包车成本设置*****************************************************
    //利率&酒店&门票配置
    //设置
    public function setvehicleinfo()
    {
        $product_id = input('id');
        $product = db("product")->find($product_id);
        if(empty($product_id) || empty($product)) $this->error("产品不存在");

        $ticketList = [];
        $ticketTotalCost = 0;

        //获取门票相关信息
        $scheduleData =  (new SDModel())->getProductScheduleData($product_id);
        $hasTicketPoiId = [];
        foreach ($scheduleData as $key=>$value){
            foreach ($value['children'] as $k=>$v){
                if($v['ticket_status']==1){
                    $hasTicketPoiId[] = $v['poiid'];
                }
            }
        }
        //获取门票列表
        if(!empty($hasTicketPoiId)){
            $ticketList = (new SDModel())->getSectionTicketData($hasTicketPoiId);
            foreach ($ticketList as $ticket_k=>$ticket_v){
                $ticketTotalCost += $ticket_v['unitBase']['amount'];
            }
        }

        $hotel_price = !empty($product['hotel_price_json'])?json_decode($product['hotel_price_json'],true):[];

        $this->assign("product",$product)
            ->assign("ticketList",$ticketList)
            ->assign("ticketTotalCost",$ticketTotalCost)
            ->assign("hotel_price",$hotel_price);

        $city = db("city")
            ->where("status",1)
            ->where(['type'=>'city','kbx_id'=>['neq','']])
            ->field("id,kbx_id,name,eng_name")
            ->select();
        $this->assign("cityList",$city);
        $this->assign("cityJson",json_encode($city));
        $hotelLevel = [
            ['level'=>5,'levelName'=>'5星级'],
            ['level'=>4,'levelName'=>'4星级'],
            ['level'=>3,'levelName'=>'3星级'],
            ['level'=>2,'levelName'=>'2星级'],
            ['level'=>1,'levelName'=>'1星级'],
        ];
        $this->assign("level",$hotelLevel);
        $this->assign("levelJson",json_encode($hotelLevel));

        $startDay = [];
        $psection = db("pschedule")
            ->field("id,title")
            ->where(['groupid'=>$product_id])
            ->order('displayorder asc')
            ->select();
        if(!empty($psection)){
            foreach ($psection as $key=>$value){
                $startDay[] = [
                    'day'=>$key+1,
                    'dayName'=>'第'.($key+1).'天',
                ];
            }
        }
        $this->assign("startDay",$startDay);
        $this->assign("startDayJson",json_encode($startDay));

        $extra_cost = $this->getExtraCostByProduct($product_id);
        $this->assign("extra_cost",$extra_cost);
        //获取货币类型
        $currencyList = (new Common())->getCurrencyListByCity();
        $this->assign("currencyList",$currencyList);

        return $this->fetch();
    }
    //获取额外成本
    public function getExtraCostByProduct($product_id)
    {
        $extra_cost = [];
        $product = db('product')->find($product_id);
        if(empty($product_id) || empty($product)) return $extra_cost;
        //额外费用 按司导分段进行设置
        $psection = db('psection')->where(['product_id'=>$product_id])->find();

        if(!empty($psection['section_json'])){
            $section_json = json_decode($psection['section_json'],true);
            $extra_cost = array_fill(0,count($section_json),['cost'=>0,'desc'=>'']);
        }
        $_extra_cost = !empty($product['extra_fee'])?explode(',',$product['extra_fee']):[];
        $_extra_desc = !empty($product['extra_fee_desc'])?explode('|',$product['extra_fee_desc']):[];
        if(!empty($extra_cost) && !empty($_extra_cost)){
            foreach ($_extra_cost as $key=>$value){
                $extra_cost[$key]['cost'] = $value??0;
                $extra_cost[$key]['desc'] = $_extra_desc[$key]??"";
            }
        }
        return $extra_cost;
    }
    //保存
    public function savePriceRate()
    {
        $post = request()->post();
        $id = $post['id']??0;
        $product = db("product")->find($id);
        if(empty($product)) $this->error("保存失败，未找到产品ID");

        //保存利率
        $vehicle_rate = $post['vehicle_rate']??0;
        $hotel_rate = $post['hotel_rate']??0;
        $ticket_rate = $post['ticket_rate']??0;
        $extra_rate = $post['extra_rate']??0;
        $extraData = $post['extraData']??[];
        $currency = $post['currency'];
        $currencySet = [];
        $currencyList = (new Common())->getCurrencyListByCity();
        foreach ( $currencyList as $currency_v){
            $currencySet[$currency_v['currency_code']] = [
                'currSymbol'=>$currency_v['currency_symbol'],
                'currName'=>$currency_v['currency_name'],
            ];
        }

        if($vehicle_rate<1 || $hotel_rate<1 || $ticket_rate<1 || $extra_rate<1){
            $this->error("请检查利率不能小于1");
        }

        $hotelArr = [];
        if(!empty($post['hotelData'])){
            $hotelArr = json_decode($post['hotelData'],true);
        }
        if(!empty($hotelArr)){
            foreach ($hotelArr as $key=>$value){
                $hotelArr[$key]['cost']['currency'] = $currency;
                $hotelArr[$key]['cost']['currSymbol'] = $currencySet[$currency]['currSymbol'];
                $hotelArr[$key]['cost']['currName'] = $currencySet[$currency]['currName'];
            }
        }
        $extraArr = [];
        $extraCost = [];
        $extraDesc = [];
        if(!empty($post['extraData'])){
            $extraArr = json_decode($post['extraData'],true);
        }
        if(!empty($extraArr)){
            foreach ($extraArr as $value){
                $e_cost = !empty($value['cost'])?$value['cost']:0;
                $extraCost[] = $e_cost;
                $extraDesc[] = $value['desc'];
            }
        }
        $extraCost = implode(',',$extraCost);
        $extraDesc = implode('|',$extraDesc);
        //保存配置
        $res = db('product')->where(['id'=>$id])->update([
            'hotel_price_json'=>json_encode($hotelArr),
            'vehicle_rate'=>$vehicle_rate,
            'hotel_rate'=>$hotel_rate,
            'ticket_rate'=>$ticket_rate,
            'extra_rate'=>$extra_rate,
            'extra_fee'=>$extraCost,
            'extra_fee_desc'=>$extraDesc,
            'currency'=>$currency,
        ]);

        if($res!==false){
            //刷新价格
            //修改利率刷新价格
            //当三种修改了任意一种 就需要刷新价格
            if($vehicle_rate==$product['vehicle_rate'] &&
                $hotel_rate==$product['hotel_rate'] &&
                $ticket_rate==$product['ticket_rate'] &&
                $extra_rate==$product['extra_rate'] &&
                $extraCost==$product['extra_fee']
            ){
                // nothing ....
            }else{
                (new ProductModel())->refreshProductTotalPrice($id);
                //刷新价格区间
                $this->updateProductPriceSection($id);
            }
            //修改了酒店利率 需要刷新酒店的售价
            if($hotel_rate!=$product['hotel_rate']){
                (new ProductModel())->updHotelCost($id,$hotel_rate);
            }

            $this->success("保存成功");
        }else{
            $this->error("保存失败");
        }
    }
    //获取
    public function getPriceSetData(){
        $post = request()->post();
        if(empty($post['product_id'])){
            return $this->error("参数product_id有误");
        }
        $product_id = $post['product_id'];
        $productData = db("product")->where("id",$product_id)->find();

        if(!empty($productData['hotel_price_json'])){
            $productData['hotel_price_json'] = json_decode($productData['hotel_price_json'],true);
        }

        $resTicketData = [];
        $poiMode = new Poi();
        $ticketData = $poiMode->getProductTicket($productData['id']);
        foreach ($ticketData as $k=>$v) {
            foreach ($v['ticket'] as $vv){
                if($vv['default']==1){
                    $resTicketData[] = $vv;
                }
            }
        }
        $exchange = db("exchange")->select();

        $resData = [
            'product'=>$productData,
            'ticket'=>$resTicketData,
            'exchange'=>$exchange
        ];

        return $this->success('ok','',$resData);
    }

    //【包车成本】价格配置提交
    public function setVehicleProductPrice()
    {
        $post = request()->post();
        $param = json_decode($post['param'],true);
        //判断日期是否重叠
        $package_id = $param['package_id'];
        db::startTrans();
        try{
            //插入数据
            if(!empty($param['more_time'])){
                $param['date'] = array_unique(array_merge($param['date'],$param['more_time']));
            }
            $res = $this->addVehiclePersonList($package_id,$param['specs'],$param['date'],$param['more_btn'],$param['hotels']);
            if(!$res){
                db::rollback();
                return json(['code'=>-1,'msg'=>'设置失败']);
            }
            db::commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败'.$e]);
        }
    }
    //写入库表
    protected function addVehiclePersonList($package_id,$specs,$date,$more_btn,$hotels){
        if(empty($specs))return false;
        if(empty($date))return false;
        $package_info = db("product_package")->where("id",$package_id)->find();
        if(empty($package_info))return false;

        $hotel_price_json = [];
        if($more_btn==1){
            $productData = db("product")->where("id",$package_info['product_id'])->field("hotel_price_json")->find();
            $hotelData = json_decode($productData['hotel_price_json'],true);
            foreach ($hotels as $k=>$v) {
                $hotelData[$k]['cost']['amount'] = $v['hotelCost'];
                $hotelData[$k]['price'] = $v['hotelCostToPrice'];
            }
            $hotel_price_json = $hotelData;
        }

        $vehicle_type = $more_btn==1 ? 2 : 1;
        if($package_info['vehicle_type']!==$vehicle_type){
            $del_res = db("product_dailyprice")->where(['package_id'=>$package_id])->delete();
            $del_res1 = db("product_specs")->where(['package_id'=>$package_id])->delete();
            //删除失败
            if($del_res===false)return false;
            if($del_res1===false)return false;
            db("product_package")
                ->where("id",$package_id)
                ->update([
                    'vehicle_type'=>$vehicle_type,
                    'updatetime'=>time()
                ]);
            //生成新的规格
            foreach ($specs as $key => $value) {
                $insertData = [
                    'package_id' => $package_id,
                    'name' => $value['name'],
                    'minorder_num' => $value['minorder_num'],
                    'inc_order_num' => $value['inc_order_num'],
                    'car_type' => $value['carType'] ?? 0,
                    'creattime' => time(),
                    'updatetime' => time(),
                    'num' => $value['num'],
                ];
                db("product_specs")->insert($insertData);
                $specs_id = db("product_specs")->getLastInsID();
                $specs[$key]['specs_id'] = $specs_id;
            }
        }else{
            $del_res = db("product_dailyprice")->where(['package_id'=>$package_id,'time'=>['in',$date]])->delete();
            //删除失败
            if($del_res===false)return false;

            if($vehicle_type==1){//纯包车  5、7、12
                foreach ($specs as $key => $value) {
                    $where['package_id'] = $package_id;
                    $where['car_type'] = $value['carType'];
                    $person = db("product_specs")->where($where)->find();
                    $specs[$key]['specs_id'] = $person['id'];
                }
            }else{//包含酒店门票  1-6人出行
                foreach ($specs as $key => $value) {
                    $where['package_id'] = $package_id;
                    $where['minorder_num'] = $value['minorder_num'];//出行人数
                    $person = db("product_specs")->where($where)->find();
                    $specs[$key]['specs_id'] = $person['id'];
                }
            }
        }

        foreach ($specs as $key => $value) {
            $insertAll = [];
            $person = db("product_specs")->where("id",$value['specs_id'])->find();
            foreach ($date as $day) {
                $insertAll[] = [
                    'product_id' => $package_info['product_id'],
                    'package_id' => $package_id,
                    'specs_id' => $value['specs_id'],
                    'name' => $person['name'],
                    'price' => $value['price'],
                    'num' => $person['num'],
                    'minorder_num' => $person['minorder_num'],
                    'inc_order_num' => $person['inc_order_num'],
                    'carType' => $value['carType'] ?? 0,
                    'time' => $day,
                    'vehicle_cost' => $value['vehicle_price']??0,
                    'hotel_cost' => $value['hotel_price']??0,
                    'ticket_cost' => $value['ticket_price']??0,
                    'extra_cost' => $value['extra_price']??0,
                    'hotel_json' => !empty($hotel_price_json)?json_encode($hotel_price_json):'',
                ];
            }

            //插入数据
            db("product_dailyprice")->insertAll($insertAll);
        }

        //更新价格区间
        $this->updateProductPriceSection($package_info['product_id']);

        return true;
    }


    //更新产品最高价&最低价
    public function updateProductPriceSection($product_id)
    {
        $product = db("product")->where("id",$product_id)->find();
        //获取目前商品的最低价和最高价
        $product_stime = date("Y-m-d",$product['sale_starttime']);
        $product_etime = date("Y-m-d",$product['sale_endtime']);
        $price_data = $this->personDayMaxAndMinPrice($product_id,$product_stime,$product_etime);
        if(!empty($price_data) && $price_data['min']<=$price_data['max']){
            $min = $price_data['min'];
            $max = $price_data['max'];
        }else{
            $min = $max = 0;
        }
        $price_section = $min.'~'.$max;
        //更新价格区间
        db('product')->where('id',$product_id)->update([
            'price_section'=>$price_section,
            'new_price_flag'=>1,
            'min_price'=>$min,
            'max_price'=>$max
        ]);
    }
    protected function personDayMaxAndMinPrice($product_id,$starttime,$endtime)
    {
        $list = db("product_dailyprice")
            ->where(["product_id"=>$product_id,"time"=>['between',[$starttime,$endtime]]])
            ->field("product_id,price,package_id,specs_id")
            ->select();

        if(empty($list)){
            return false;
        }else{
            $packageList = array_column($list,"package_id");
            if(empty($packageList)){
                return false;
            }else{
                $packageList = array_unique($packageList);
                $package_where['id'] = ["in",$packageList];
                $package_where['status'] = 1;
                $packageData = db("product_package")->where($package_where)->column("id");
                if(empty($packageData)){
                    return false;
                }else{
                    $min = $max = $list[0]['price'];
                    foreach ($list as $key=>$value){
                        if(in_array($value['package_id'],$packageData)){
                            $min = $min < $value['price']?$min:$value['price'];
                            $max = $max > $value['price']?$max:$value['price'];
                        }
                    }
                    return ["min"=>$min,"max"=>$max];
                }
            }
        }
    }


    //*****************************************************************************
    //**********************价格配置  End***********************************************















    //增加新的产品信息
    public function pronotice()
    {
        $product_id = input('id',0);
        if(empty($product_id)) return $this->error('产品ID有误');
        $product = db('product')->find($product_id);
        if(empty($product)) return $this->error('产品不存在');
        $data = db('product_notice')->where('product_id',$product_id)->find();
        if(!empty($data)){
            $data['assembleimgs'] = array_values(array_filter(explode(',',$data['assemble_address_img'])));
            $data['ticketimgs'] = array_values(array_filter(explode(',',$data['exchange_ticket_img'])));
            $pick_up_address_json = '';
            $assemble_address_json = '';
            if(!empty($data['pick_up_address_json'])){
                $pick_up_address_json = json_decode($data['pick_up_address_json'],true);
                foreach ($pick_up_address_json as $key=>$value){
                    $pick_up_address_json[$key]['format'] = json_encode($value['format']);
                }
            }
            if(!empty($data['assemble_address_json'])){
                $assemble_address_json = json_decode($data['assemble_address_json'],true);
                foreach ($assemble_address_json as $key=>$value){
                    $assemble_address_json[$key]['format'] = json_encode($value['format']);
                }
            }
            $data['pick_up_address_json'] = $pick_up_address_json;
            $data['assemble_address_json'] = $assemble_address_json;
        }
        $this->assign('id',$product_id);
        $this->assign('data',$data);
        //货币单位
        $currencyList = (new Common())->getCurrencyListByCity();
        $this->assign('currencyList',$currencyList);
        return $this->fetch();
    }

    //保存新的产品提醒信息
    public function updpronotice()
    {
        $post = request()->post();
        $product_id = input('id',0);
        if(empty($product_id)) return $this->result([],0,'产品ID有误');
        $product = db('product')->field('item_num')->find($product_id);
        if(empty($product)) return $this->result([],0,'产品不存在');
        //去除多余的键值
        unset($post['pick_up_time'],$post['pick_up_address'],$post['pick_up_address_format']);
        unset($post['assemble_time'],$post['assemble_address'],$post['assemble_address_format'],$post['assemble_address_img']);

        $data = db('product_notice')->where('product_id',$product_id)->find();
        $post['assemble_address_img'] = $post['assemble_address_img']??[];
        $post['assemble_address_img'] = implode(',',$post['assemble_address_img']);
        $post['exchange_ticket_img'] = $post['exchange_ticket_img']??[];
        $post['exchange_ticket_img'] = implode(',',$post['exchange_ticket_img']);
        $post['pick_up_address_json'] = str_replace('replace_and','&',$post['pick_up_address_json']);
        $post['assemble_address_json'] = str_replace('replace_and','&',$post['assemble_address_json']);
        if(empty($data)){
            //新增
            $post['product_id'] = $product_id;
            $post['product_code'] = $product['item_num'];
            $res = db('product_notice')->insert($post);
        }else{
            //更新
            $res = db('product_notice')->where('product_id',$product_id)->update($post);
        }

        if($res!==false){
            return $this->result([],200,'更新成功');
        }else{
            return $this->result([],0,'更新失败');
        }
    }


    //审核产品
    //20200315 注：被审核产品也可能已上架，审核操作照旧，如果未上架执行上架操作，已上架则忽略上架操作
    public function checkSupplierStatus()
    {
        $post = request()->post();
        if(empty($post['id'])) return $this->result([],-1,'缺少参数id','json');
        if(!in_array($post['check_status'],[2,3])){
            return $this->result([],-1,'缺少参数check_status','json');
        }

        $res = db('product')->where('id',$post['id'])->update([
           'check_status'=>$post['check_status'],
           'check_admin_id'=>Cookie::get('admin'),
           'check_time'=>time()
        ]);
        if($res){
            if($post['check_status']==2){
                $standardtrip = db('standardtrip')->where('trip_id',$post['id'])->find();
                $gt_model = new GT();
                $product = $gt_model->getTripData($standardtrip['trip_id']);
                $lineSummary = $gt_model->getTripSummary($product);
                $toursLineTitle = !empty($lineSummary) ? implode("\n",$lineSummary) : '';
                $standard = db('standard')->where('id',$standardtrip['sid'])->find();
                //行程路线
                db('standardtrip')->where('trip_id',$post['id'])->update([
                    'toursLineTitle'=>$toursLineTitle
                ]);
                //修改tob的上架状态 202003 未上架执行上架操作
                if(empty($standard['show_toB'])) db('standard')->where('id',$standardtrip['sid'])->update(['show_toB'=>1]);
                //上架产品的操作流程
                //更新产品的售价
                (new Product())->updateProductBasePriceSection($post['id']);
                //推送标品到ES
                (new Esapi())->refreshStandardDataToES($standardtrip['sid']);
                //通知相应供应商上架该商品
                (new KbxOrder())->putOnSaleNotifyToKbx($standardtrip['sid']);
                if(!empty($standard['supplier_admin_id']) && empty($standard['show_toB'])){
                    //直接上架分销商小程序对应的产品
                    $supplierAdminInfo = (new Common())->getSupplierAdminInfo($standard['supplier_admin_id']);
                    if(!empty($supplierAdminInfo['company_id'])){
                        (new KbxOrder())->onSaleWxSoftSupplierStandard($standardtrip['sid'],$supplierAdminInfo['company_id']);
                    }
                }
                //首次审核产品上架通知
                (new SDModel())->setOnSaleNoticeAtFirst($standardtrip['sid']);

                return $this->result([],200,'审核成功','json');
            }
        }else{
            return $this->result([],-1,'审核失败','json');
        }
    }

    //更换供应商
    public function changeSupplierId()
    {
        $id = input('id',0);
        if(empty($id)) return $this->error('参数错误');
        $product = db('product')->find($id);
        if(empty($product)) return $this->error('产品信息有误');
        //提交操作
        if(request()->isPost()){
            $post = request()->post();
            $supplier = $post['supplier']??'';
            if(empty($supplier)) return $this->error('请选择供应商');
            //查找对应供应商的超级管理员
            $supplierAdmin = db('supplier_admin')->where([
                'company_id'=>$supplier,
                'is_super'=>1
            ])->find();
            //判断是否重复分发给同一供应商
            if(!empty($product['supplier_admin_id'])){
                $supplierAdminInfo = (new Common())->getSupplierAdminInfo($product['supplier_admin_id']);
                if(!empty($supplierAdminInfo['company_id']) && $supplierAdminInfo['company_id']==$supplier){
                    return $this->error('该产品已归属所选供应商，请勿重复操作！');
                }
            }
            db::startTrans();
            try{
                //产品
                db('product')->where('id',$id)->update([
                    'supplier_id'=>$supplier,
                    'supplier_admin_id'=>$supplierAdmin['supplier_admin_id']??0,
                    'update_time'=>time(),
                ]);
                $goods = db('goods')->where('goods_tcode',$product['item_num'])->find();
                //商品
                if(!empty($goods['goods_id'])){
                    db('goods')->where('goods_id',$goods['goods_id'])->update([
                        'supplier_admin_id'=>$supplierAdmin['supplier_admin_id']??0,
                        'supplier_id'=>$supplier
                    ]);
                    db('standard')->where('goods_id',$goods['goods_id'])->update([
                        'supplier_admin_id'=>$supplierAdmin['supplier_admin_id']??0
                    ]);
                    $standard = db('standard')->field("id")->where('goods_id',$goods['goods_id'])->find();
                    //同步信息到订单系统
                    if(!empty($standard['id'])){
                        (new KbxOrder())->changeSupplierToKBXSystem($standard['id'],$supplier);
                    }
                }

                db::commit();
                return $this->success('修改成功');
            }catch (Exception $e){
                db::rollback();
                return $this->error('修改失败,'.$e->getMessage());
            }
        }
        //非提交操作
        $where['is_super'] = 1;
        $where['is_use'] = 1;
        $supplierList = db('supplier_admin')->field('supplier_name,company_id')
            ->where($where)//超级管理员
            ->group('company_id')->select();
        foreach ($supplierList as $key=>$value){
            if(empty($value['company_id'])) unset($supplierList[$key]);
        }
        $this->assign('supplierList',$supplierList);
        $this->assign('supplier_id',$product['supplier_id']??'');
        $this->assign('id',$id);
        return $this->fetch();
    }

    //获取POI分类
    public function getPoiClassifyList()
    {
        $poiClassifyList = db('classify')
            ->field('classify_id as id,classify_name as name')
            ->where(['is_use'=>1,'classify_id'=>['gt',10]])
            ->select();
        array_unshift($poiClassifyList,['id'=>4,'name'=>'酒店']);
        array_unshift($poiClassifyList,['id'=>3,'name'=>'送机']);
        array_unshift($poiClassifyList,['id'=>2,'name'=>'接机']);
        array_unshift($poiClassifyList,['id'=>1,'name'=>'POI']);
        $poiClassifyList[] = ['id'=>6,'name'=>'其他'];
        return $poiClassifyList;
    }

    //获取全局节点类型数组
    public function getGlobalActiveTypeList()
    {
        $poiClassifyList = db('classify')
            ->field('classify_id as id,classify_name as name')
            ->where(['is_use'=>1,'classify_id'=>['gt',10]])
            ->select();
        $global_active_type_arr = array_column($poiClassifyList,'id');
        array_unshift($global_active_type_arr,4);
        array_unshift($global_active_type_arr,1);

        return $global_active_type_arr;
    }

    //包含结算账户的supplie列表
    public function getSupplierList()
    {
        $KbxOther = new KbxOther();
        $supplierArr = $KbxOther->kbx_suppliers_list();
        $supplier = array();
        $supplierNameArr = array();
        foreach ($supplierArr as $k=>$v) {
            if(empty($v['id']) || empty($v['name'])){
                continue;
            }
            $supplier[$k]['id'] = $v['id']??'';
            $supplier[$k]['name'] = $v['name']??'unknown';
            $supplierNameArr[$v['id']] = $v['name']??'unknown';
        }

        return [$supplier,$supplierNameArr];
    }

    //获取全部的供应商账号
    public function getAllSupplierList()
    {
        $KbxOther = new KbxOther();
        $supplierArr = $KbxOther->kbx_all_suppliers_list();
        $supplier = array();
        $supplierNameArr = array();
        foreach ($supplierArr as $k=>$v) {
            if(empty($v['id']) || empty($v['name'])){
                continue;
            }
            $supplier[$k]['id'] = $v['id']??'';
            $supplier[$k]['name'] = $v['name']??'unknown';
            $supplierNameArr[$v['id']] = $v['name']??'unknown';
        }

        return [$supplier,$supplierNameArr];
    }

    //-------------------------------------供应商基价模式设置套餐核价模型-------------------------------------
    //设置查看套餐
    public function setBasePackage(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $table_name = ['规格名称','库存','最低下单数','最小增长数'];

        //是新增操作
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post()['data'];

            Db::startTrans(); //启动事务
            try {
                //********************套餐********************
                //将全部套餐status都设置为2
                Db::name('product_base_package')->where("product_id",$id)->update(['status'=>2]);

                $packageData['product_id'] = $id;
                foreach ($post as $key=>$value){
                    $packageData['name'] = $value['package_name'];
                    $packageData['status'] = 1;
                    if(!empty($value['package_id'])){
                        $packageData['updatetime'] = time();
                        Db::name('product_base_package')->where("id",$value['package_id'])->update($packageData);

                        //********************规格********************
                        $specsData['package_id'] = $value['package_id'];
                        $specsData['updatetime'] = time();
                        $specsData['status'] = 1;
                        if(!empty($value['specsdata'])){
                            //将全部规格status都设置为2
                            Db::name('product_base_specs')->where("package_id",$value['package_id'])->update(['status'=>2]);
                            foreach ($value['specsdata'] as $k=>$v){
                                $specsData['name'] = $v['specs_name'];
                                $specsData['num'] = $v['specs_num'];
                                $specsData['minorder_num'] = $v['minorder_num'];
                                $specsData['inc_order_num'] = $v['inc_order_num'];
                                $specsData['special'] = $v['specs_special']??0;

                                if(!empty($v['specs_id'])){
                                    Db::name('product_base_specs')->where("id",$v['specs_id'])->update($specsData);
                                    //更新关联的库存
                                    Db::name('product_base_dailyprice')->where(['specs_id'=>$v['specs_id']])->update([
                                        'num'=>$specsData['num']
                                    ]);
                                }else{
                                    $specsData['creattime'] = time();
                                    Db::name('product_base_specs')->insert($specsData);
                                }
                            }
                        }
                    }else{
                        $packageData['creattime'] = time();
                        $packageData['updatetime'] = time();
                        Db::name('product_base_package')->insert($packageData);

                        $package_id = Db::name('product_base_package')->getLastInsID();//规格id
                        $specsData['package_id'] = $package_id;
                        $specsData['creattime'] = time();
                        $specsData['updatetime'] = time();
                        $specsData['status'] = 1;
                        if(!empty($value['specsdata'])){
                            foreach ($value['specsdata'] as $k=>$v){
                                $specsData['name'] = $v['specs_name'];
                                $specsData['num'] = $v['specs_num'];
                                $specsData['minorder_num'] = $v['minorder_num'];
                                $specsData['inc_order_num'] = $v['inc_order_num'];
                                $specsData['special'] = $v['specs_special']??0;

                                Db::name('product_base_specs')->insert($specsData);
                            }
                        }
                    }
                }
                $this->updateProductBasePriceMode($id,true);
                Db::commit(); //提交事务

                //删除套餐数据
                $this->delBaseSpecsAndPerson($id);

                return $this->success(Lang::get('设置成功'));
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error(Lang::get('设置失败'));
            }
        }else{
            $package = Db::name('product_base_package')->where("product_id",$id)->where("status",1)->select();
            if($package){
                foreach($package as $key=>$value){
                    $package[$key]['specs'] = [];
                    $package_id = $value['id'];
                    $package[$key]['specs'] = Db::name('product_base_specs')->where("package_id",$package_id)->where("status",1)->select();
                }
                $this->assign('package',$package);
            }else{
                $this->assign('package','');
            }
        }
        $this->assign('id',$id);
        $this->assign('table_name',$table_name);
        return $this->fetch();
    }
    //是否开启基价模式设置
    protected function updateProductBasePriceMode($product_id,$flag)
    {
        $base_price_mode = $flag?'1':'0';
        return db('product')->where('id',$product_id)->update(['base_price_mode'=>$base_price_mode]);
    }
    //删除套餐数据
    protected function delBaseSpecsAndPerson($id)
    {
        $product = db("product")->where("id",$id)->field("id")->find();
        if(!empty($product)){
            $packageIdArr = db("product_base_package")->where(["product_id"=>$id,"status"=>2])->column("id");
            if(!empty($packageIdArr)){
                DB::startTrans();//开启事务
                try{
                    //直接删除套餐后，规格价格也一并删除
                    db("product_base_package")->where(["product_id"=>$id,"status"=>2,"id"=>["in",$packageIdArr]])->delete();
                    $specsIdArr = db("product_specs")->where(["package_id"=>["in",$packageIdArr]])->column("id");
                    db("product_base_specs")->where(["package_id"=>["in",$packageIdArr]])->delete();
                    db("product_base_dailyprice")->where(["specs_id"=>["in",$specsIdArr]])->delete();
                    //更新价格区间
                    //$this->updateProductBasePriceSection($id);
                    //提交事务
                    DB::commit();
                    return true;
                }catch(\PDOException $e){
                    //回滚事务
                    DB::rollback();
                    return false;
                }
            }
        }
    }
    //ajax删除套餐
    public function delBasePackage()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $package = db("product_base_package")->where("id",$post['id'])->find();
            if(empty($package)){
                return json(['code'=>-1,"msg"=>'删除失败']);
            }

            db::startTrans();
            try{
                db("product_base_package")->delete($post['id']);
                $specsIdArr = db("product_base_specs")->where("package_id",$post['id'])->column("id");
                db("product_base_specs")->where("package_id",$post['id'])->delete();
                db("product_base_dailyprice")->where(["specs_id"=>["in",$specsIdArr]])->delete();
                //更新价格区间
                //$this->updateProductBasePriceSection($package['product_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }
    //ajax删除规格
    public function delBaseSpecs()
    {
        $post = request()->post();
        if(!isset($post['id'])&&empty($post['id'])){
            return json(['code'=>-1,"msg"=>'参数有误']);
        }else{
            $specs = db("product_base_specs")->where("id",$post['id'])->find();
            if(empty($specs)){
                return json(['code'=>-2,"msg"=>'删除失败']);
            }
            $package = db("product_base_package")->where("id",$specs['package_id'])->find();
            if(empty($package)){
                return json(['code'=>-3,"msg"=>'删除失败']);
            }

            db::startTrans();
            try{
                db("product_base_specs")->where("id",$post['id'])->delete();
                db("product_base_dailyprice")->where("specs_id",$specs['id'])->delete();
                //更新价格区间
                $this->updateProductPriceSection($package['product_id']);
                db::commit();
                return json(['code'=>200,"msg"=>'删除成功']);
            }catch(Exception $e){
                db::rollback();
                return json(['code'=>-1,"msg"=>'删除失败']);
            }
        }
    }
    //展示价格页面
    public function showProductBasePrice()
    {
        return $this->fetch();
    }
    //设置价格页面
    public function setProductBasePrice()
    {
        $id = input('id',0);
        if(empty($id)) return $this->error('参数有误');
        $product = db('product')->find($id);
        //货币
        $currency = !empty($product['currency'])?db('city')->where('currency_code',$product['currency'])->find():[];
        $product['currency_symbol'] = !empty($currency)?$currency['currency_symbol']:'￥';
        //套餐
        $packageList =	db('product_base_package')->where('product_id',$id)->where('status',1)->select();
        $this->assign('product_id',$id);
        $product['currency'] = !empty($product['currency'])?$product['currency']:"CNY";
        $this->assign('product',$product);
        $this->assign('packageList',$packageList);
        //获取货币类型列表
        $currencyCodeList = (new Common())->getCurrencyListByCity();
        foreach ($currencyCodeList as $key=>$value){
            $currencyCodeList[$key]['currency_all_name'] = $value['currency_name'].'('.$value['currency_code'].')';
        }
        $this->assign("currencyCodeList",$currencyCodeList);
        return $this->fetch();
    }
    //ajax查詢规格
    public function getProductBaseSpecByPackageId(){
        $package_id = input('package_id');
        $list =	db('product_base_specs')->where('package_id',$package_id)->where('status',1)->select();
        return json($list);
    }
    //不存在套餐时 默认生成套餐A
    public function setDefaultBaseSpec($product_id){
        //检测是否存在产品
        $product = db("product")->find($product_id);
        if(empty($product_id) || empty($product)) return false;
        //检测是否已经存在套餐 如存在直接跳过
        $package = db("product_base_package")->where(['product_id'=>$product_id])->find();
        if(!empty($package)) return false;
        //生成新套餐
        $res = db('product_base_package')->insert([
            "product_id"=>$product_id,
            "name"=>"套餐A",
            "status"=>1,
            "creattime"=>time(),
            "updatetime"=>time(),
        ]);
        return $res;
    }

    //getPriceForMake被productmake调用
    public function getBasePriceForMake($product_id){
        $product = db("product")->find($product_id);
        //判断是否存在默认套餐
        $this->setDefaultSpec($product_id);
        //派单价格
        $carPriceArr = ['f_cost'=>0,'s_cost'=>0,'t_cost'=>0];
        $standard = db("standard")
            ->alias("s")
            ->join("standardtrip st","s.id=st.sid","left")
            ->where("st.trip_id",$product_id)
            ->field("s.*")
            ->find();
        if(!empty($standard)){
            //查询已配置过的派单价格
            $psection = db("psection")
                ->alias("p")
                ->join("standardtrip s","p.product_id=s.trip_id","left")
                ->where("s.sid",$standard['id'])
                ->field("p.*")
                ->select();
            if(!empty($psection)){
                foreach ($psection as $key=>$value) {
                    $section_json = json_decode($value['section_json'],true);
                    $price = 0;
                    if(!empty($section_json)){
                        foreach ($section_json as $k=>$v) {
                            $price += intval($v);
                        }
                    }
                    if($value['car_type']==1){
                        $carPriceArr['f_cost'] = $price;
                    }elseif($value['car_type']==10){
                        $carPriceArr['s_cost'] = $price;
                    }elseif($value['car_type']==20){
                        $carPriceArr['t_cost'] = $price;
                    }
                }
            }
        }

        $currencySet = [];
        $currencyList = (new Common())->getCurrencyListByCity();
        foreach ( $currencyList as $currency_v){
            $currencySet[$currency_v['currency_code']] = [
                'currSymbol'=>$currency_v['currency_symbol'],
                'currName'=>$currency_v['currency_name'],
            ];
        }
        $exchangeData = db("exchange")->select();
        $exchange = [];
        foreach ($exchangeData as $k=>$v) {
            $exchange[$v['currency_code']] = $v['exchange_rate'];
        }

        $currencyCode = !empty($product['currency']) ? $product['currency'] : 'USD';
        $currency = $currencySet[$currencyCode]['currSymbol'];
        $currencyName = $currencySet[$currencyCode]['currName'];
        $exchangeNum = $exchange[$currencyCode]??'';

        $starttime = date("Y-m-d",$product['sale_starttime']);
        $endtime = date("Y-m-d",$product['sale_endtime']);
        $dailyPrice = db("product_base_dailyprice")->where(["product_id"=>$product_id,'time'=>['between',[$starttime,$endtime]]])->order("id asc")->select();
        //按天封装数据
        $data = [];
        foreach ($dailyPrice as $value){
            $data[$value['time'].",".$value['package_id']][] = $value;
        }
        $this->assign('product',$product)
            ->assign('data',(string)json_encode($data))
            ->assign('starttime',$starttime)
            ->assign('endtime',$endtime)
            ->assign('currency',$currency)
            ->assign('currencyName',$currencyName)
            ->assign('exchangeNum',$exchangeNum)
            ->assign('carPriceArr',$carPriceArr);

        return true;
    }

    //ajax设置产品基价
    public function ajaxSetProductBasePrice()
    {
        $post = request()->post();
        $product_id = $post['product_id']??0;
        $date = $post['date']??[];
        $price =  $post['price']??[];
        if(empty($date)) return $this->error('请选择日期');
        if(empty($price)) return $this->error('请填写价格');

        db::startTrans();
        try{
            //插入数据
            $this->addBasePersonList($price,$date,$product_id);

            db::commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        }catch(Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>'设置失败'.$e->getMessage()]);
        }
    }

    //写入库表
    protected function addBasePersonList($specs,$date,$product_id){
        if(empty($specs))return false;
        if(empty($date))return false;
        $insertAll = [];
        foreach ($specs as $key=>$value){
            $spec = db('product_base_specs')->find($value['spec_id']);
            if(empty($spec)) return false;
            $del_res = db("product_base_dailyprice")
                ->where(['specs_id'=>$value['spec_id'],'time'=>['in',$date]])
                ->delete();
            //删除已有套餐日期价格数据
            if($del_res===false)return false;
            foreach ($date as $day) {
                $insertAll[] = [
                    'time' => $day,
                    'product_id' => $product_id,
                    'package_id' => $spec['package_id'],
                    'specs_id' => $spec['id'],
                    'name' => $spec['name'],
                    'total_cost' => $value['total_cost'],
                    'price' => $value['price'],
                    'num' => $spec['num'],
                    'minorder_num' => $spec['minorder_num'],
                    'inc_order_num' => $spec['inc_order_num'],
                ];
            }
        }
        //插入数据
        db("product_base_dailyprice")->insertAll($insertAll);
        db('product')->where('id',$product_id)->update(['kbx_set_market_price'=>1]);
        //更新价格区间
        //$this->updateProductBasePriceSection($product_id);
    }
    //单独设置某天的价格
    public function setSingleDayBasePrice($dailyprice_id,$price,$total_cost)
    {
        $dailyprice = db("product_base_dailyprice")->find($dailyprice_id);
        if(empty($dailyprice)) return $this->error(Lang::get("修改失败"));
        db::startTrans();
        try{
            db("product_base_dailyprice")->where('id',$dailyprice_id)->update(['price'=>$price,'total_cost'=>$total_cost]);
            //更新价格区间
            //$this->updateProductBasePriceSection($dailyprice['product_id']);
            db::commit();
            return json(['code'=>200,'msg'=>Lang::get("修改成功")]);
        }catch (Exception $e){
            db::rollback();
            return json(['code'=>-1,'msg'=>Lang::get("修改失败").',原因是'.$e->getMessage()]);
        }
    }

    //更新产品最高价&最低价
    public function updateProductBasePriceSection($product_id)
    {
        $product = db("product")->find($product_id);
        //获取目前商品的最低价和最高价
        $product_stime = date("Y-m-d",$product['sale_starttime']);
        $product_etime = date("Y-m-d",$product['sale_endtime']);
        $price_data = $this->personDayMaxAndMinBasePrice($product_id,$product_stime,$product_etime);
        if(!empty($price_data) && $price_data['min']<=$price_data['max']){
            $min = $price_data['min'];
            $max = $price_data['max'];
        }else{
            $min = $max = 0;
        }
        $price_section = $min.'~'.$max;
        //更新价格区间
        db('product')->where('id',$product_id)->update([
            'price_section'=>$price_section,
            'new_price_flag'=>1,
            'min_price'=>$min,
            'max_price'=>$max,
            'base_price_mode'=>1//开启基价模式
        ]);
    }
    protected function personDayMaxAndMinBasePrice($product_id,$starttime,$endtime)
    {
        $list = db("product_base_dailyprice pd")
            ->join('product_base_specs ps','ps.id=pd.specs_id','left')
            ->where([
                "pd.product_id"=>$product_id,
                "pd.time"=>['between',[$starttime,$endtime]],
                "ps.special"=>['lt',1]//特殊规格不参与价格统计
            ])
            ->field("pd.product_id,pd.price,pd.package_id,pd.specs_id")
            ->select();

        if(empty($list)){
            return false;
        }else{
            $packageList = array_column($list,"package_id");
            if(empty($packageList)){
                return false;
            }else{
                $packageList = array_unique($packageList);
                $package_where['id'] = ["in",$packageList];
                $package_where['status'] = 1;
                $packageData = db("product_base_package")->where($package_where)->column("id");
                if(empty($packageData)){
                    return false;
                }else{
                    $min = $max = $list[0]['price'];
                    foreach ($list as $key=>$value){
                        if(in_array($value['package_id'],$packageData)){
                            $min = $min < $value['price']?$min:$value['price'];
                            $max = $max > $value['price']?$max:$value['price'];
                        }
                    }
                    return ["min"=>$min,"max"=>$max];
                }
            }
        }
    }

    //根据月份获取套餐信息
    public function getBaseDailypriceByMonth($product_id,$year,$month)
    {
//        $product_id = input('product_id',0,'int');
//        $year = input('year',0,'int');
//        $month = input('month',0,'int');
        $month_value = $month>9?$month:"0".$month;
        $start_day = $year.'-'.$month_value.'-01';
        if($month>=12){
            $year+=1;$month_value="01";
        }else{
            $month+=1;
            $month_value = $month>9?$month:"0".$month;
        }
        $end_day = $year.'-'.$month_value.'-01';
        //大于等于start_day 小于end_day
        $base_dailyprice = db('product_base_dailyprice')->where([
            'product_id'=>$product_id,
            'time'=>['between',[$start_day,$end_day]]
        ])->field('time,min(price) as price,min(total_cost) as cost')->group('time')->select();
        //var_dump(db()->getLastSql());
        $this->success('success','',$base_dailyprice);
    }
    //根据日期获取套餐信息
    public function getBaseDailypriceByDate($package_id,$date)
    {
        //大于等于start_day 小于end_day
        $base_dailyprice = db('product_base_dailyprice')->where([
            'package_id'=>$package_id,
            'time'=>$date
        ])->select();
        //var_dump(db()->getLastSql());
        $this->success('success','',$base_dailyprice);
    }

    //根据所选日期删除价格日历
    public function delBasePriceByDate()
    {
        $post = request()->post();
        $product_id = $post['product_id']??0;
        $start_time = $post['start_time']??'';
        $end_time = $post['end_time']??'';
        $package_ids = $post['package_ids']??[];

        $product = db('product')->find($product_id);
        if(empty($product_id) || empty($product)) return $this->error('产品错误');

        if(empty($start_time) || empty($end_time)) return $this->error('日期选择错误');
        if(empty($package_ids)) return $this->error('请选择套餐');

        db::startTrans();
        try{

            db('product_base_dailyprice')->where([
                'product_id'=>$product_id,
                'package_id'=>['in',$package_ids],
                'time'=>[['egt',$start_time],['elt',$end_time]]
            ])->delete();

            //更新价格区间
            //$this->updateProductBasePriceSection($product_id);
            db::commit();
            return $this->success(Lang::get('删除成功'));
        }catch(Exception $e){
            db::rollback();
            return $this->error(Lang::get('删除失败').','.Lang::get('原因是').$e->getMessage());
        }


    }

    //设置套餐的利润点
    public function setBasePackageRate()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $table_name = ['规格名称','库存','最低下单数','最小增长数','结算价','B端利润点','B端售价'];

        //是新增操作
        if ($this->request->isPost()) {
            //是提交操作
            $post = $this->request->post()['data'];

            Db::startTrans(); //启动事务
            try {
                //********************套餐********************
                $packageData['product_id'] = $id;
                $kbx_set_market_price = false;
                foreach ($post as $key=>$value){
                    if(!empty($value['package_id'])){
                        //********************规格********************
                        if(!empty($value['specsdata'])){
                            //将全部规格status都设置为2
                            foreach ($value['specsdata'] as $k=>$v){
                                $salePrice = $v['salePrice']??0;
                                unset($v['salePrice']);
                                $specsData['bdj_rate'] = $v['bdj_rate'];
                                if(!empty($v['specs_id'])){
                                    Db::name('product_base_specs')->where("id",$v['specs_id'])->update($specsData);
                                }
                                if(!empty($salePrice)){
                                    //更新日历价格的建议销售价
//                                    db('product_base_dailyprice')->where(['specs_id'=>$v['specs_id'],'price'=>['eq',0]])->update(['price'=>$salePrice]);
                                    db('product_base_dailyprice')->where(['specs_id'=>$v['specs_id']])->update(['price'=>$salePrice]);
                                    $kbx_set_market_price = true;
                                }
                            }
                        }
                    }
                }
                //管理员设置建议销售价
                if($kbx_set_market_price){
                    db('product')->where('id',$id)->update(['kbx_set_market_price'=>1]);
                }
                Db::commit(); //提交事务
                return $this->success(Lang::get('设置成功'));
            } catch (\PDOException $e) {
                Db::rollback(); //回滚事务
                return $this->error(Lang::get('设置失败'));
            }
        }else{
            $package = Db::name('product_base_package')->where("product_id",$id)->where("status",1)->select();
            //检测是否设置建议销售价
            $correctTip = $isSetSalePrice = false;
            $tipMsg = '';
            $specs_id = [];
            if($package){
                foreach($package as $key=>$value){
                    $package[$key]['specs'] = [];
                    $package_id = $value['id'];
                    $specs = Db::name('product_base_specs')->where("package_id",$package_id)->where("status",1)->select();
                    foreach ($specs as $s_key=>$s_value){
                        $dayprice = db('product_base_dailyprice')->field('total_cost,price')
                            ->where(['specs_id'=>$s_value['id'],'time'=>['egt',date('Y-m-d')]])
                            ->find();
                        $specs[$s_key]['total_cost'] = $dayprice['total_cost']??0;
                        $specs[$s_key]['sale_price'] = $dayprice['price']??0;
                    }
                    $specs_id += array_column($specs,'id');
                    $package[$key]['specs'] = $specs;
                }
                $this->assign('package',$package);
                if(!empty($specs_id)){
                    $totalBaseDailyPrice = db('product_base_dailyprice')->where([
                        'specs_id'=>['in',$specs_id]
                    ])->count();
                    $noPriceBaseDailyPrice = db('product_base_dailyprice')->where([
                        'specs_id'=>['in',$specs_id],
                        'price'=>0
                    ])->count();
                    if(empty($totalBaseDailyPrice)){
                        $tipMsg="供应商暂未设置日期价格！";
                    }elseif($totalBaseDailyPrice==$noPriceBaseDailyPrice){
                        $isSetSalePrice = true;
                        $tipMsg="供应商暂未设置建议销售价！";
                    }elseif($noPriceBaseDailyPrice > 0 && $totalBaseDailyPrice > $noPriceBaseDailyPrice){
                        $isSetSalePrice = true;
                        $tipMsg="供应商暂只设置部分建议销售价！确认是否有0元的商品";
                    }else{
                        $correctTip = true;
                        $tipMsg = '供应商已设置日期价格和建议销售价';
                    }
                }else{
                    $tipMsg="供应商暂未设置规格！";
                }

            }else{
                $tipMsg="供应商暂未设置套餐！";
                $this->assign('package','');
            }
            $this->assign('tipMsg',$tipMsg);
            $this->assign('isSetSalePrice',$isSetSalePrice);
            $this->assign('correctTip',$correctTip);
        }
        $this->assign('id',$id);
        $product = db('product')->where('id',$id)->find();
        $this->assign('product',$product);
        $this->assign('table_name',$table_name);
        return $this->fetch();
    }

    //开启基价模式
    public function openBasePriceMode($id)
    {
        if(empty($id)) return $this->error('错误');
        $product = db('product')->find($id);
        if(empty($product)) return $this->error('错误');
        db::startTrans();
        try{
            $this->updateProductBasePriceSection($id);
            db::commit();
            $this->success('成功');
        }catch(Exception $e){
            db::rollback();
            $this->error('失败，'.$e->getMessage());
        }
    }

    //通过package_id获取售卖月份
    public function getSaleMonthByPackageId($package_id)
    {
        if(empty($package_id) || $package_id < 1) return $this->error('fail');
        //大于等于start_day 小于end_day
        $base_daily_date= db('product_base_dailyprice')->where([
            'package_id'=>$package_id
        ])->group('time')->column('time');
        $months = [];
        $dateArr = [];
        foreach ($base_daily_date as $value){
            $show_date = date("Y年m月",strtotime($value));
            $year = date("Y",strtotime($value));
            $month = date("m",strtotime($value));
            if(!in_array($show_date,$months)){
                $months[] = $show_date;
                $dateArr[] = ['show_date'=>$show_date,'year'=>$year,'month'=>$month];
            }
        }
        //var_dump(db()->getLastSql());
        $this->success('success','',$dateArr);
    }

    //通过package_id和month获取售卖价格
    public function getSalePriceByPackageIdAndMonth($package_id,$year,$month)
    {

        if(empty($package_id) || $package_id < 1) return $this->error('fail');
        if(empty($year) || empty($month)) return $this->error('fail');
        $year = intval($year);
        $month = intval($month);
        $month_value = $month>9?$month:"0".$month;
        $start_day = $year.'-'.$month_value.'-01';
        if($month>=12){
            $year+=1;$month_value="01";
        }else{
            $month+=1;
            $month_value = $month>9?$month:"0".$month;
        }
        $end_day = $year.'-'.$month_value.'-01';
        //大于等于start_day 小于end_day
        $base_dailyprice = db('product_base_dailyprice')->where([
            'package_id'=>$package_id,
            'time'=>[['between',[$start_day,$end_day]],['lt',$end_day]]
        ])->field('time,min(price) as price,min(total_cost) as cost')->group('time')->select();
//        var_dump(db()->getLastSql());
        $this->success('success','',$base_dailyprice);
    }

    public function saveCustomerContent($id,$contents)
    {
        if(empty($id)) return $this->error('请求错误');
        if(empty($contents)) return $this->error('请添加或补充所有的标题和内容');
        $product = db('product')->find($id);
        if(empty($product)) return $this->error('请求错误');

        foreach ($contents as $content){
            if(empty($content) || empty($content['title']) || empty($content['content'])){
                return $this->error('请添加或补充所有的标题和内容');
            }
        }

        $res = db('product')->where('id',$id)->update(['customer_content'=>json_encode($contents)]);
        if($res!==false){
            return $this->success('更新成功');
        }else{
            return $this->error('更新失败');
        }
    }

    public function delCustomerContent($id,$index)
    {
        if(empty($id)) return $this->error('请求错误');
        $product = db('product')->find($id);
        if(empty($product['customer_content'])) return $this->error('请求错误');

        $contents = json_decode($product['customer_content'],true);
        unset($contents[$index-1]);//删除对应下标的数据
        $res = db('product')->where('id',$id)->update(['customer_content'=>json_encode($contents)]);
        if($res!==false){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败');
        }
    }

    //切换行程方案的模式
    public function changeTextPlan()
    {
        $post = request()->post();
        $productId = $post['id']??'';
        $is_text_plan = $post['is_text_plan']??0;

        if(empty($productId)) return $this->error('缺少行程ID!');
        $product = db('product')->find($productId);
        if(empty($product)) return $this->error('请求错误！');

        //将详情【sale_details】覆盖到计划方案【text_plan】
        $updData['is_text_plan'] = $is_text_plan;
        if($is_text_plan > 0 && !empty($product['sale_details'])) $updData['text_plan'] = $product['sale_details'];
        $res = db('product')->where('id',$productId)->update($updData);
        if($res!==false){
            return $this->success('切换成功');
        }else{
            return $this->error('切换失败');
        }
    }

    //发送产品更新邮件提醒
    public function sendEmailNoticeToAgent()
    {
        $post = request()->post();
        $standardId = $post['id']??'';
        $content = $post['content']??'';
        if(empty($standardId)) return $this->error('缺少参数ID!');
        if(empty($content)) return $this->error('请填写邮件提醒内容!');

        $standard = db('standard')->find($standardId);
        if(empty($standard)) return $this->error('请求错误！');

        $res = (new SDModel())->putOnSaleNotifyV2ToKbx($standardId,$content);
        if(isset($res['msg'])){
            return $this->error($res['msg']);
        }else{
            return $this->success('发送成功');
        }

    }

    //通过节点获取线路详情
    public function getProductLineDetails($product_id=0)
    {
        if(empty($product_id)) return "";
        $schedules = db('pschedule')->where(['groupid'=>$product_id])->select();
        if(empty($schedules)) return "";
        $schedule_ids = array_column($schedules,'id');
        $actives = db('pactive a')
            ->join("city c","c.id=a.cityid",'left')
            ->join("poi p","p.id=a.poiid",'left')
            ->field("a.*,c.lat as c_lat,c.lng as c_lng,
            p.introduce as p_introduce,p.lat,p.lng,p.thumb as poi_thumb,p.eng_introduce,
            p.open_time,p.ticket,p.price,p.grade,p.description,p.thumb,
            p.source,p.mobile,p.ticket_url,p.address")
            ->where(['a.groupid'=>['in',$schedule_ids]])
            ->order('a.groupid,a.displayorder')
            ->select();

        $html = $this->getLineContentHtmlV2($schedules,$actives);
        return $html;
    }
    //第一版匹配html【废弃】
    public function getLineContentHtml($schedules,$actives)
    {
        $html = "<style>p{margin: 0;}</style>";
        foreach ($schedules as $key=>$value){
            $html .= "<div style='width:800px;line-height:40px;margin: 0 auto;'>
                        <div style='color:#f90;font-size:16px;border-top: 1px solid #eee;text-align: center;margin:20px 0 0 0;font-weight:bold;'><strong>第".($key + 1)."天<span style='margin-left: 10px'>".$value['title']."</div>";

            foreach ($actives as $k=>$v){
                if($v['groupid']==$value['id']){
                    $poi_name = '';
                    if(!empty($v['poiname'])){
                        $poi_name = $v['poiname'];
                    }elseif(!empty($v['cityname'])){
                        $poi_name = $v['cityname'];
                    }elseif(!empty($v['title'])){
                        $poi_name =$v['title'];
                    }
                    if(!empty($poi_name)) $html .= "<div style='line-height: 25px;padding: 0 4px;background: #ffb800;display: inline-block;margin: 8px 0 0 50px;font-weight: bold;'>".$poi_name."</div>";
                    if(!empty($v['poi_content'])) $html .= "<div style='color: #7e7e7e;margin:0 0 0 50px;'>".$v['poi_content']."</div>";
                    if(!empty($v['content'])) $html .= "<div style='margin:0 0 0 50px;'>".$v['content']."</div>";

                    $thumb_imgs = array_merge(explode(',',$v['poi_thumb']??''),explode(',',$v['poiImg']??''));
                    $thumb_imgs = array_values(array_unique(array_filter($thumb_imgs)));
                    $other_imgs = explode(',',$v['other_images']??'');
                    $other_imgs = array_values(array_unique(array_filter($other_imgs)));
                    if(!empty($thumb_imgs) && count($thumb_imgs)) $thumb_imgs = array_slice($thumb_imgs,0,2);
                    if(!empty($other_imgs) && count($other_imgs)) $other_imgs = array_slice($other_imgs,0,2);
                    if(!empty($thumb_imgs)){
                        $html .= "<div class='imgbox' id='imgbox39015' style='margin:5px 0 10px 50px;'>";
                        for ($i=0;$i<count($thumb_imgs);$i++){
                            $html .= "  <img style='width: 48%;height:240px;' src='".$thumb_imgs[$i]."'>";
                        }
                        $html .= "</div>";
                    }

                    if(!empty($other_imgs)){
                        $html .= "<div class='imgbox' id='imgbox39015' style='margin:5px 0 10px 50px;'>";
                        for ($i=0;$i<count($other_imgs);$i++){
                            $html .= "  <img style='width: 48%;height:240px;' src='".$other_imgs[$i]."'>";
                        }
                        $html .= "</div>";

                    }
                }
            }

            $html .= "</div>";
        }
        return $html;
    }

    public function getLineContentHtmlV2($schedules,$actives)
    {
        $html = "";
        foreach ($schedules as $key=>$value){
            $html .= '<h3 class="previewtitle" style="margin: 20px 0px 0px; padding: 0px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-align: center; color: rgb(255, 153, 0); font-size: 16px; border-top: 1px solid rgb(238, 238, 238);">
                        <a style="color: rgb(51, 51, 51); font-family: &quot;Helvetica Neue&quot;, Helvetica, &quot;PingFang SC&quot;, 微软雅黑, Tahoma, Arial, sans-serif; font-size: 16px; white-space: normal;"><strong>第'.($key + 1).'天<span style="margin-left: 10px">'.$value["title"].'</strong></a>
                    </h3>';
            foreach ($actives as $k=>$v){
                if($v['groupid']==$value['id']){
                    $poi_name = '';
                    if(!empty($v['poiname'])){
                        $poi_name = $v['poiname'];
                    }elseif(!empty($v['cityname'])){
                        $poi_name = $v['cityname'];
                    }elseif(!empty($v['title'])){
                        $poi_name =$v['title'];
                    }
                    $thumb_imgs = array_merge(explode(',',$v['poi_thumb']??''),explode(',',$v['poiImg']??''));
                    $thumb_imgs = array_values(array_unique(array_filter($thumb_imgs)));
                    $other_imgs = explode(',',$v['other_images']??'');
                    $other_imgs = array_values(array_unique(array_filter($other_imgs)));
                    if(!empty($thumb_imgs) && count($thumb_imgs)) $thumb_imgs = array_slice($thumb_imgs,0,2);
                    if(!empty($other_imgs) && count($other_imgs)) $other_imgs = array_slice($other_imgs,0,2);
                    $thumb_imgs = array_merge($thumb_imgs,$other_imgs);
                    $thumb_imgs_html = '';
                    $thumb_imgs_arr = [];
                    if(!empty($thumb_imgs)){
                        foreach ($thumb_imgs as $t_value){
                            $thumb_imgs_arr[] = '<img src="'.$t_value.'" alt="" style="display: inline-block; vertical-align: middle; border: none; width: 360px; margin: 0px 4px 10px; height: 240px;"/>';
                        }
                        $thumb_imgs_html = implode('&nbsp;',$thumb_imgs_arr);
                    }

                    $html .= '<p class="sub_day_title" style="margin-top: 0px; margin-bottom: 0px; padding: 0px 4px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); line-height: 25px; background: rgb(255, 184, 0); display: inline-block;">'.$poi_name.'</p>';
//                    $v['poi_content'] = str_replace('<br>','',$v['poi_content']);
//                    $v['content'] = str_replace('<br>','',$v['content']);
                    if(!empty($v['poi_content'])) $html .= '<span style="color:#7e7e7e">'.$v['poi_content'].'</span>';
                    if(!empty($v['content'])) $html .= '<div>'.$v['content'].'</div>';
                    $html .= '<p>'.$thumb_imgs_html.'</p>';
                }
            }

            $html .= "</div>";
        }
        return $html;
    }

    //通过线路生成售卖详情 2020 11 13
    public function createProductSalesContent($id=0)
    {
        if(empty($id)) return $this->error('error');
        $product = db('product')->find($id);
        if(empty($product)) return $this->error('error');
        $result['content'] = $this->getProductLineDetails($id);
        $this->result($result,200,'success','json');
    }

    //产品附件列表
    public function product_attachment(Request $request)
    {
        $pro_id = $request->param('id',0,'int');
        if(empty($pro_id)) return $this->error('请求错误');
        $where['product_id'] = $pro_id;
        $where['is_delete'] = 0;
        $result = db('product_attachments')->where($where)->order('create_time desc')->select();
        foreach ($result as $key=>$value){
            $result[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
        }
        $this->assign('list',$result);
        $this->assign('product_id',$pro_id);
        return $this->fetch();
    }

    //创建产品附件
    public function create_pro_attachment(Request $request)
    {
        $id = $request->param('id',0,'int');
        if(empty($id)) return $this->error('缺少产品ID');
        $this->assign('product_id',$id);
        return $this->fetch();
    }

    //下载附件
    public function download_pro_attachment(Request $request){

        $file_id = $request->param('file_id',0,'int');
        if(empty($file_id)) return $this->error('请求错误');
        $pro_attachment = db('product_attachments')->find($file_id);
        if(empty($pro_attachment)) return $this->error('附件已删除或不存在');

        $fileurl = trim($pro_attachment['file_url']);
        $info = get_headers($fileurl, true);
        $size = $info['Content-Length'];
        header("Content-type:application/octet-stream");
        header("Content-Disposition:attachment;filename = " . $pro_attachment['file_name']);
        header("Accept-ranges:bytes");
        header("Accept-length:" . $size);
        readfile($fileurl);
        exit;
    }

    //ota 配置项
    public function ota_config(Request $request)
    {
        $product_id = $request->param('product_id',0);
        if(empty($product_id)) return $this->error('请求错误');
        $product = db('product')->find($product_id);
        if(empty($product_id)) return $this->error('产品不存在或已失效');

        $where['product_id'] = $product_id;
        $ota_config = db('product_ota')->where($where)->find();
        if(empty($ota_config)){
            db('product_ota')->insert([
                'product_id'=>$product_id,
                'create_time'=>time()
            ]);
            $ota_config = $where;
        }
        //取消政策 最少两条 最多5条
        if(empty($ota_config['cancel_rules'])){
            $ota_config['cancel_rules'] = [
                '-1_30_10_10_0',
                '29_1_30_30_0',
                '0_0_100_100_0',
            ];
        }else{
            $ota_config['cancel_rules'] = explode(',',$ota_config['cancel_rules']);
        }
        $this->assign('ota_config',$ota_config);
        $this->assign('product',$product);

        $itemTypes = (new FliggyApi())->getItemTypes();
        $itemTypes = array_keys($itemTypes);
        $this->assign('itemTypes',$itemTypes);

        return $this->fetch();
    }

    public function update_ota_config(Request $request)
    {
        if($request->isPost()){
            $validate = new Validate([
                'product_id'=>'require',
                'ota_images'=>'require',
                'cancel_rules'=>'require',
            ],[
                'product_id.require'=>'请求错误',
                'ota_images.require'=>'请至少上传一张主图',
                'cancel_rules.require'=>'请补充取消政策',
            ]);
            if(!$validate->check($request->post())){
                return $this->error('提交失败，'.$validate->getError());
            }
            $post = $request->post();
            $post['update_time'] = time();
            $post['bc_start_date'] = !empty($post['bc_start_date']) ?
                strtotime($post['bc_start_date']) : 0;
            $post['start_combo_date'] = !empty($post['start_combo_date']) ?
                strtotime($post['start_combo_date']) : 0;
            $post['end_combo_date'] = !empty($post['end_combo_date']) ?
                strtotime($post['end_combo_date']) : 0;

            unset($post['product_id']);
            $res = db('product_ota')->where(['product_id'=>$request->post('product_id')])->update($post);
            if($res!==false){
                return $this->success('更新成功');
            }else{
                return $this->error('更新失败');
            }
        }else{
            return $this->error('请以POST方法提交');
        }
    }

    //ota 配置项
    public function ota_ticket_config(Request $request)
    {
        $product_id = $request->param('product_id',0);
        if(empty($product_id)) return $this->error('请求错误');
        $where['product_id'] = $product_id;
        $product = db('product')
            ->where([
                'id'=>$product_id,
                'service_type'=>2,//服务类型为门票
            ])->find();
        if(empty($product)) return $this->error('非门票产品禁止设置！');

        $ota_config = db('product_ota_ticket')->where($where)->find();
        if(empty($ota_config)){
            db('product_ota_ticket')->insert([
                'product_id'=>$product_id,
                'create_time'=>time()
            ]);
            $ota_config = $where;
        }

        $this->assign('ota_config',$ota_config);
        return $this->fetch();
    }

    public function update_ota_ticket_config(Request $request)
    {
        if($request->isPost()){
            $validate = new Validate([
                'product_id'=>'require',
                'inventory_type'=>'require',
                'need_enter_date'=>'require',
            ],[
                'product_id.require'=>'请求错误',
                'inventory_type.require'=>'请选择库存类型',
                'need_enter_date.require'=>'请选择是否需要买家指定入园日期',
            ]);
            if(!$validate->check($request->post())){
                return $this->error('提交失败，'.$validate->getError());
            }

            //预定时间限制 限制规则
            if(!empty($request->post['reserve_limit_type']) && $request->post['reserve_limit_type']==2){
                $validate2 = new Validate([
                    'reserve_limit_day'=>'require',
                    'reserve_limit_per_time'=>'require',
                    'reserve_limit_enter_time'=>'require',
                ],[
                    'reserve_limit_day.require'=>'请输入提前购买天数',
                    'reserve_limit_per_time.require'=>'请输入提前购买的最晚时间',
                    'reserve_limit_enter_time.require'=>'请输入当日票购买后需等待时间',
                ]);
                if(!$validate2->check($request->post())){
                    return $this->error('提交失败，'.$validate->getError());
                }
            }


            //预定时间限制 限制规则
            if(!empty($request->post['code_mode']) && in_array($request->post['code_mode'],[1,2])){
                $validateCodeModeMsg = [
                    'expiry_date_start.require'=>'请输入电子凭证有效期开始时间',
                    'expiry_date_end.require'=>'请输入电子凭证有效期结束时间',
                    'expiry_days.require'=>'请输入电子凭证有效期天数',
                    'package_id.require'=>'请输入核销门店库id',
                    'merchant_name.require'=>'请输入核销服务提供商',
                ];
                $validateCodeMode = [
                    'package_id'=>'require',
                    'merchant_name'=>'require',
                ];
                if($request->post['expiry_date_type']==1){
                    $validateCodeMode['expiry_date_start'] = $validateCodeMode['expiry_date_end'] = 'require';
                }elseif($request->post['expiry_date_type']==2){
                    $validateCodeMode['expiry_date_end'] = 'require';
                }elseif($request->post['expiry_date_type']==3){
                    $validateCodeMode['expiry_days'] = 'require';
                }
                $validate3 = new Validate($validateCodeMode,$validateCodeModeMsg);
                if(!$validate3->check($request->post())){
                    return $this->error('提交失败，'.$validate->getError());
                }

            }

            $post = $request->post();
            $post['update_time'] = time();

            unset($post['product_id']);
            $res = db('product_ota_ticket')
                ->where(['product_id'=>$request->post('product_id')])
                ->update($post);
            if($res!==false){
                return $this->success('更新成功');
            }else{
                return $this->error('更新失败');
            }
        }else{
            return $this->error('请以POST方法提交');
        }
    }


    //虚拟产品供应商
    protected function electronicSupplier()
    {
        return [
            ['key'=>'Lvji','name'=>'驴迹旅行']
        ];
    }

    public function saveProductElectronic($product_id,$data)
    {
        if(empty($product_id) || empty($data)) return false;
        $exist = db('product_electronic')->where(['electronic_pro_id'=>$product_id])->find();
        if(!empty($exist)){
            $updateData = [];
            //创建关联的电子商品信息
            $allow_field = ['electronic_tpl_id','electronic_validate',
                'electronic_source','electronic_cost_price','electronic_refer_price','electronic_scenic_spots',
                'electronic_poi_name','electronic_supplier','electronic_scenic_latlng'];
            //过滤需要更新的字段信息
            $data_keys = array_keys($data);
            foreach ($allow_field as $value){
                if(in_array($value,$data_keys)){
                    $updateData[$value] = $value == 'electronic_tpl_id' ?
                        rawurldecode($data[$value]) : $data[$value];
                }
            }
            if(!empty($updateData)) db('product_electronic')->where(['electronic_pro_id'=>$product_id])->update($updateData);
        }else{
            $geohash = '';
            if(!empty($post['electronic_latlng'])){
                $electronic_latlng = json_decode($post['electronic_scenic_latlng'],true);
                if(!empty($electronic_latlng)){
                    $lat = $electronic_latlng['lat'];
                    $lng = $electronic_latlng['lng'];
                    $geohash = GeoHash::encode($lng,$lat);
                }
            }
            //创建关联的电子商品信息
            db('product_electronic')->insert([
                'electronic_pro_id'=>$product_id,
                'electronic_tpl_id'=>rawurldecode($post['electronic_tpl_id']??''),
                'electronic_validate'=>$post['electronic_validate']??0,
                'electronic_source'=>$post['electronic_source']??'',
                'electronic_cost_price'=>$post['electronic_cost_price']??0,
                'electronic_refer_price'=>$post['electronic_refer_price']??0,
                'electronic_scenic_spots'=>$post['electronic_scenic_spots']??'',
                'electronic_poi_name'=>$post['electronic_poi_name']??'',
                'electronic_supplier'=>$post['electronic_supplier']??'',
                'electronic_scenic_latlng'=>$post['electronic_scenic_latlng']??'',
                'electronic_scenic_geohash'=>$geohash,
            ]);
        }

    }

    //获取虚拟电子产品的信息
    public function verifyTplId(Request $request)
    {
        if(!$request->isPost()) return $this->error('请以POST方式提交');
        $tplId = $request->post('tplId','');
        if(empty($tplId)) return $this->error('缺少tplId参数');
        $result = (new LvjiApi())->getScenicLink($tplId,false);
        if(empty($result['link'])){
            return $this->error('暂未查询到关联的虚拟商品！');
        }
        return $this->success('success','',$result);
    }
}
